
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" lang="zh_Hans">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>表单字段 &#8212; Django 3.2.11.dev 文档</title>
    <link rel="stylesheet" href="../../_static/default.css" type="text/css" />
    <link rel="stylesheet" href="../../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../../" src="../../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../../_static/jquery.js"></script>
    <script type="text/javascript" src="../../_static/underscore.js"></script>
    <script type="text/javascript" src="../../_static/doctools.js"></script>
    <script type="text/javascript" src="../../_static/language_data.js"></script>
    <link rel="index" title="索引" href="../../genindex.html" />
    <link rel="search" title="搜索" href="../../search.html" />
    <link rel="next" title="模型表单函数" href="models.html" />
    <link rel="prev" title="表单 API" href="api.html" />



 
<script src="../../templatebuiltins.js"></script>
<script>
(function($) {
    if (!django_template_builtins) {
       // templatebuiltins.js missing, do nothing.
       return;
    }
    $(document).ready(function() {
        // Hyperlink Django template tags and filters
        var base = "../templates/builtins.html";
        if (base == "#") {
            // Special case for builtins.html itself
            base = "";
        }
        // Tags are keywords, class '.k'
        $("div.highlight\\-html\\+django span.k").each(function(i, elem) {
             var tagname = $(elem).text();
             if ($.inArray(tagname, django_template_builtins.ttags) != -1) {
                 var fragment = tagname.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + tagname + "</a>");
             }
        });
        // Filters are functions, class '.nf'
        $("div.highlight\\-html\\+django span.nf").each(function(i, elem) {
             var filtername = $(elem).text();
             if ($.inArray(filtername, django_template_builtins.tfilters) != -1) {
                 var fragment = filtername.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + filtername + "</a>");
             }
        });
    });
})(jQuery);</script>

  </head><body>

    <div class="document">
  <div id="custom-doc" class="yui-t6">
    <div id="hd">
      <h1><a href="../../index.html">Django 3.2.11.dev 文档</a></h1>
      <div id="global-nav">
        <a title="Home page" href="../../index.html">Home</a>  |
        <a title="Table of contents" href="../../contents.html">Table of contents</a>  |
        <a title="Global index" href="../../genindex.html">Index</a>  |
        <a title="Module index" href="../../py-modindex.html">Modules</a>
      </div>
      <div class="nav">
    &laquo; <a href="api.html" title="表单 API">previous</a>
     |
    <a href="../index.html" title="API 参考" accesskey="U">up</a>
   |
    <a href="models.html" title="模型表单函数">next</a> &raquo;</div>
    </div>

    <div id="bd">
      <div id="yui-main">
        <div class="yui-b">
          <div class="yui-g" id="ref-forms-fields">
            
  <div class="section" id="s-module-django.forms.fields">
<span id="s-form-fields"></span><span id="module-django.forms.fields"></span><span id="form-fields"></span><h1>表单字段<a class="headerlink" href="#module-django.forms.fields" title="永久链接至标题">¶</a></h1>
<dl class="class">
<dt id="django.forms.Field">
<em class="property">class </em><code class="descname">Field</code>(<em>**kwargs</em>)<a class="headerlink" href="#django.forms.Field" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>当你创建一个 <code class="docutils literal notranslate"><span class="pre">Form</span></code> 类时，最重要的部分是定义表单的字段。每个字段都有自定义的验证逻辑，以及其他一些钩子。</p>
<dl class="method">
<dt id="django.forms.Field.clean">
<code class="descclassname">Field.</code><code class="descname">clean</code>(<em>value</em>)<a class="headerlink" href="#django.forms.Field.clean" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>虽然你使用 <code class="docutils literal notranslate"><span class="pre">Field</span></code> 类的主要方式是在 <code class="docutils literal notranslate"><span class="pre">Form</span></code> 类中，但你也可以将它们实例化并直接使用，以更好地了解它们的工作方式。每个 <code class="docutils literal notranslate"><span class="pre">Field</span></code> 实例都有一个 <code class="docutils literal notranslate"><span class="pre">clean()</span></code> 方法，它接收一个参数，并引发一个 <code class="docutils literal notranslate"><span class="pre">django.core.exceptions.ValidationError</span></code> 异常或返回干净的值：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">django</span> <span class="kn">import</span> <span class="n">forms</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span> <span class="o">=</span> <span class="n">forms</span><span class="o">.</span><span class="n">EmailField</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="o">.</span><span class="n">clean</span><span class="p">(</span><span class="s1">&#39;foo@example.com&#39;</span><span class="p">)</span>
<span class="go">&#39;foo@example.com&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="o">.</span><span class="n">clean</span><span class="p">(</span><span class="s1">&#39;invalid email address&#39;</span><span class="p">)</span>
<span class="gt">Traceback (most recent call last):</span>
<span class="c">...</span>
<span class="gr">ValidationError</span>: <span class="n">[&#39;Enter a valid email address.&#39;]</span>
</pre></div>
</div>
<div class="section" id="s-core-field-arguments">
<span id="s-id1"></span><span id="core-field-arguments"></span><span id="id1"></span><h2>核心字段参数<a class="headerlink" href="#core-field-arguments" title="永久链接至标题">¶</a></h2>
<p>每个 <code class="docutils literal notranslate"><span class="pre">Field</span></code> 类的构造函数至少需要这些参数。有些 <code class="docutils literal notranslate"><span class="pre">Field</span></code> 类需要额外的、特定的字段参数，但以下参数应 <em>始终</em> 接受：</p>
<div class="section" id="s-required">
<span id="required"></span><h3><code class="docutils literal notranslate"><span class="pre">required</span></code><a class="headerlink" href="#required" title="永久链接至标题">¶</a></h3>
<dl class="attribute">
<dt id="django.forms.Field.required">
<code class="descclassname">Field.</code><code class="descname">required</code><a class="headerlink" href="#django.forms.Field.required" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>默认情况下，每个 <code class="docutils literal notranslate"><span class="pre">Field</span></code> 类都假定值是必填的，所以如果你传递一个空值—— <code class="docutils literal notranslate"><span class="pre">None</span></code> 或空字符串（<code class="docutils literal notranslate"><span class="pre">&quot;&quot;</span></code>）——那么 <code class="docutils literal notranslate"><span class="pre">clean()</span></code> 将引发一个 <code class="docutils literal notranslate"><span class="pre">ValidationError</span></code> 异常：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">django</span> <span class="kn">import</span> <span class="n">forms</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span> <span class="o">=</span> <span class="n">forms</span><span class="o">.</span><span class="n">CharField</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="o">.</span><span class="n">clean</span><span class="p">(</span><span class="s1">&#39;foo&#39;</span><span class="p">)</span>
<span class="go">&#39;foo&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="o">.</span><span class="n">clean</span><span class="p">(</span><span class="s1">&#39;&#39;</span><span class="p">)</span>
<span class="gt">Traceback (most recent call last):</span>
<span class="c">...</span>
<span class="gr">ValidationError</span>: <span class="n">[&#39;This field is required.&#39;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="o">.</span><span class="n">clean</span><span class="p">(</span><span class="kc">None</span><span class="p">)</span>
<span class="gt">Traceback (most recent call last):</span>
<span class="c">...</span>
<span class="gr">ValidationError</span>: <span class="n">[&#39;This field is required.&#39;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="o">.</span><span class="n">clean</span><span class="p">(</span><span class="s1">&#39; &#39;</span><span class="p">)</span>
<span class="go">&#39; &#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="o">.</span><span class="n">clean</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>
<span class="go">&#39;0&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="o">.</span><span class="n">clean</span><span class="p">(</span><span class="kc">True</span><span class="p">)</span>
<span class="go">&#39;True&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="o">.</span><span class="n">clean</span><span class="p">(</span><span class="kc">False</span><span class="p">)</span>
<span class="go">&#39;False&#39;</span>
</pre></div>
</div>
<p>要指定一个字段是 <em>不必填</em> 的，传递 <code class="docutils literal notranslate"><span class="pre">required=False</span></code> 给 <code class="docutils literal notranslate"><span class="pre">Field</span></code> 构造函数：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">f</span> <span class="o">=</span> <span class="n">forms</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">required</span><span class="o">=</span><span class="kc">False</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="o">.</span><span class="n">clean</span><span class="p">(</span><span class="s1">&#39;foo&#39;</span><span class="p">)</span>
<span class="go">&#39;foo&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="o">.</span><span class="n">clean</span><span class="p">(</span><span class="s1">&#39;&#39;</span><span class="p">)</span>
<span class="go">&#39;&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="o">.</span><span class="n">clean</span><span class="p">(</span><span class="kc">None</span><span class="p">)</span>
<span class="go">&#39;&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="o">.</span><span class="n">clean</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>
<span class="go">&#39;0&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="o">.</span><span class="n">clean</span><span class="p">(</span><span class="kc">True</span><span class="p">)</span>
<span class="go">&#39;True&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="o">.</span><span class="n">clean</span><span class="p">(</span><span class="kc">False</span><span class="p">)</span>
<span class="go">&#39;False&#39;</span>
</pre></div>
</div>
<p>如果一个 <code class="docutils literal notranslate"><span class="pre">Field</span></code> 有 <code class="docutils literal notranslate"><span class="pre">required=False</span></code>，而你给 <code class="docutils literal notranslate"><span class="pre">clean()</span></code> 传递一个空值，那么 <code class="docutils literal notranslate"><span class="pre">clean()</span></code> 将返回一个 <em>规范化</em> 的空值，而不是引发 <code class="docutils literal notranslate"><span class="pre">ValidationError</span></code>。对于 <code class="docutils literal notranslate"><span class="pre">CharField</span></code>，将返回 <a class="reference internal" href="#django.forms.CharField.empty_value" title="django.forms.CharField.empty_value"><code class="xref py py-attr docutils literal notranslate"><span class="pre">empty_value</span></code></a>，默认为一个空字符串。对于其他 <code class="docutils literal notranslate"><span class="pre">Field</span></code> 类，它可能是 <code class="docutils literal notranslate"><span class="pre">None</span></code>。（这因字段而异。）</p>
<p>必填表单字段的部件有 <code class="docutils literal notranslate"><span class="pre">required</span></code> HTML 属性。将 <a class="reference internal" href="api.html#django.forms.Form.use_required_attribute" title="django.forms.Form.use_required_attribute"><code class="xref py py-attr docutils literal notranslate"><span class="pre">Form.use_required_attribute</span></code></a> 属性设置为 <code class="docutils literal notranslate"><span class="pre">False</span></code> 就可以禁用。由于在添加和删除表单集时，浏览器的验证可能不正确，所以表单集的表单中不包含 <code class="docutils literal notranslate"><span class="pre">required</span></code> 属性。</p>
</div>
<div class="section" id="s-label">
<span id="label"></span><h3><code class="docutils literal notranslate"><span class="pre">label</span></code><a class="headerlink" href="#label" title="永久链接至标题">¶</a></h3>
<dl class="attribute">
<dt id="django.forms.Field.label">
<code class="descclassname">Field.</code><code class="descname">label</code><a class="headerlink" href="#django.forms.Field.label" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p><code class="docutils literal notranslate"><span class="pre">label</span></code> 参数让你指定该字段的“人类友好”标签。当 <code class="docutils literal notranslate"><span class="pre">Field</span></code> 在 <code class="docutils literal notranslate"><span class="pre">Form</span></code> 中显示时，会用到这个标签。</p>
<p>如上文“将表格输出为 HTML”中所解释的，<code class="docutils literal notranslate"><span class="pre">Field</span></code> 的默认标签是由字段名通过将所有下划线转换为空格并将第一个字母大写而生成的。如果默认行为不能产生一个适当的标签，请指定 <code class="docutils literal notranslate"><span class="pre">label</span></code>。</p>
<p>这是一个完整的 <code class="docutils literal notranslate"><span class="pre">Form</span></code> 例子，它的两个字段实现了 <code class="docutils literal notranslate"><span class="pre">label</span></code>。我们指定 <code class="docutils literal notranslate"><span class="pre">auto_id=False</span></code> 以简化输出：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">django</span> <span class="kn">import</span> <span class="n">forms</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">CommentForm</span><span class="p">(</span><span class="n">forms</span><span class="o">.</span><span class="n">Form</span><span class="p">):</span>
<span class="gp">... </span>    <span class="n">name</span> <span class="o">=</span> <span class="n">forms</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">label</span><span class="o">=</span><span class="s1">&#39;Your name&#39;</span><span class="p">)</span>
<span class="gp">... </span>    <span class="n">url</span> <span class="o">=</span> <span class="n">forms</span><span class="o">.</span><span class="n">URLField</span><span class="p">(</span><span class="n">label</span><span class="o">=</span><span class="s1">&#39;Your website&#39;</span><span class="p">,</span> <span class="n">required</span><span class="o">=</span><span class="kc">False</span><span class="p">)</span>
<span class="gp">... </span>    <span class="n">comment</span> <span class="o">=</span> <span class="n">forms</span><span class="o">.</span><span class="n">CharField</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span> <span class="o">=</span> <span class="n">CommentForm</span><span class="p">(</span><span class="n">auto_id</span><span class="o">=</span><span class="kc">False</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">f</span><span class="p">)</span>
<span class="go">&lt;tr&gt;&lt;th&gt;Your name:&lt;/th&gt;&lt;td&gt;&lt;input type=&quot;text&quot; name=&quot;name&quot; required&gt;&lt;/td&gt;&lt;/tr&gt;</span>
<span class="go">&lt;tr&gt;&lt;th&gt;Your website:&lt;/th&gt;&lt;td&gt;&lt;input type=&quot;url&quot; name=&quot;url&quot;&gt;&lt;/td&gt;&lt;/tr&gt;</span>
<span class="go">&lt;tr&gt;&lt;th&gt;Comment:&lt;/th&gt;&lt;td&gt;&lt;input type=&quot;text&quot; name=&quot;comment&quot; required&gt;&lt;/td&gt;&lt;/tr&gt;</span>
</pre></div>
</div>
</div>
<div class="section" id="s-label-suffix">
<span id="label-suffix"></span><h3><code class="docutils literal notranslate"><span class="pre">label_suffix</span></code><a class="headerlink" href="#label-suffix" title="永久链接至标题">¶</a></h3>
<dl class="attribute">
<dt id="django.forms.Field.label_suffix">
<code class="descclassname">Field.</code><code class="descname">label_suffix</code><a class="headerlink" href="#django.forms.Field.label_suffix" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p><code class="docutils literal notranslate"><span class="pre">label_suffix</span></code> 参数可以让你在每个字段的基础上覆盖表单的 <a class="reference internal" href="api.html#django.forms.Form.label_suffix" title="django.forms.Form.label_suffix"><code class="xref py py-attr docutils literal notranslate"><span class="pre">label_suffix</span></code></a>：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">ContactForm</span><span class="p">(</span><span class="n">forms</span><span class="o">.</span><span class="n">Form</span><span class="p">):</span>
<span class="gp">... </span>    <span class="n">age</span> <span class="o">=</span> <span class="n">forms</span><span class="o">.</span><span class="n">IntegerField</span><span class="p">()</span>
<span class="gp">... </span>    <span class="n">nationality</span> <span class="o">=</span> <span class="n">forms</span><span class="o">.</span><span class="n">CharField</span><span class="p">()</span>
<span class="gp">... </span>    <span class="n">captcha_answer</span> <span class="o">=</span> <span class="n">forms</span><span class="o">.</span><span class="n">IntegerField</span><span class="p">(</span><span class="n">label</span><span class="o">=</span><span class="s1">&#39;2 + 2&#39;</span><span class="p">,</span> <span class="n">label_suffix</span><span class="o">=</span><span class="s1">&#39; =&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span> <span class="o">=</span> <span class="n">ContactForm</span><span class="p">(</span><span class="n">label_suffix</span><span class="o">=</span><span class="s1">&#39;?&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">f</span><span class="o">.</span><span class="n">as_p</span><span class="p">())</span>
<span class="go">&lt;p&gt;&lt;label for=&quot;id_age&quot;&gt;Age?&lt;/label&gt; &lt;input id=&quot;id_age&quot; name=&quot;age&quot; type=&quot;number&quot; required&gt;&lt;/p&gt;</span>
<span class="go">&lt;p&gt;&lt;label for=&quot;id_nationality&quot;&gt;Nationality?&lt;/label&gt; &lt;input id=&quot;id_nationality&quot; name=&quot;nationality&quot; type=&quot;text&quot; required&gt;&lt;/p&gt;</span>
<span class="go">&lt;p&gt;&lt;label for=&quot;id_captcha_answer&quot;&gt;2 + 2 =&lt;/label&gt; &lt;input id=&quot;id_captcha_answer&quot; name=&quot;captcha_answer&quot; type=&quot;number&quot; required&gt;&lt;/p&gt;</span>
</pre></div>
</div>
</div>
<div class="section" id="s-initial">
<span id="initial"></span><h3><code class="docutils literal notranslate"><span class="pre">initial</span></code><a class="headerlink" href="#initial" title="永久链接至标题">¶</a></h3>
<dl class="attribute">
<dt id="django.forms.Field.initial">
<code class="descclassname">Field.</code><code class="descname">initial</code><a class="headerlink" href="#django.forms.Field.initial" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p><code class="docutils literal notranslate"><span class="pre">initial</span></code> 参数让你指定在未绑定的 <code class="docutils literal notranslate"><span class="pre">Form</span></code> 中渲染这个 <code class="docutils literal notranslate"><span class="pre">Field</span></code> 时要使用的初始值。</p>
<p>要指定动态初始数据，请参见 <a class="reference internal" href="api.html#django.forms.Form.initial" title="django.forms.Form.initial"><code class="xref py py-attr docutils literal notranslate"><span class="pre">Form.initial</span></code></a> 参数。</p>
<p>这个用法是当你想显示一个“空”的表单，其中一个字段被初始化为一个特定的值。例如：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">django</span> <span class="kn">import</span> <span class="n">forms</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">CommentForm</span><span class="p">(</span><span class="n">forms</span><span class="o">.</span><span class="n">Form</span><span class="p">):</span>
<span class="gp">... </span>    <span class="n">name</span> <span class="o">=</span> <span class="n">forms</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">initial</span><span class="o">=</span><span class="s1">&#39;Your name&#39;</span><span class="p">)</span>
<span class="gp">... </span>    <span class="n">url</span> <span class="o">=</span> <span class="n">forms</span><span class="o">.</span><span class="n">URLField</span><span class="p">(</span><span class="n">initial</span><span class="o">=</span><span class="s1">&#39;http://&#39;</span><span class="p">)</span>
<span class="gp">... </span>    <span class="n">comment</span> <span class="o">=</span> <span class="n">forms</span><span class="o">.</span><span class="n">CharField</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span> <span class="o">=</span> <span class="n">CommentForm</span><span class="p">(</span><span class="n">auto_id</span><span class="o">=</span><span class="kc">False</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">f</span><span class="p">)</span>
<span class="go">&lt;tr&gt;&lt;th&gt;Name:&lt;/th&gt;&lt;td&gt;&lt;input type=&quot;text&quot; name=&quot;name&quot; value=&quot;Your name&quot; required&gt;&lt;/td&gt;&lt;/tr&gt;</span>
<span class="go">&lt;tr&gt;&lt;th&gt;Url:&lt;/th&gt;&lt;td&gt;&lt;input type=&quot;url&quot; name=&quot;url&quot; value=&quot;http://&quot; required&gt;&lt;/td&gt;&lt;/tr&gt;</span>
<span class="go">&lt;tr&gt;&lt;th&gt;Comment:&lt;/th&gt;&lt;td&gt;&lt;input type=&quot;text&quot; name=&quot;comment&quot; required&gt;&lt;/td&gt;&lt;/tr&gt;</span>
</pre></div>
</div>
<p>你可能会想，为什么不在显示表单时传递一个初始值的字典作为数据呢？好吧，如果你这样做，你会触发验证，HTML 输出将包括任何验证错误：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">CommentForm</span><span class="p">(</span><span class="n">forms</span><span class="o">.</span><span class="n">Form</span><span class="p">):</span>
<span class="gp">... </span>    <span class="n">name</span> <span class="o">=</span> <span class="n">forms</span><span class="o">.</span><span class="n">CharField</span><span class="p">()</span>
<span class="gp">... </span>    <span class="n">url</span> <span class="o">=</span> <span class="n">forms</span><span class="o">.</span><span class="n">URLField</span><span class="p">()</span>
<span class="gp">... </span>    <span class="n">comment</span> <span class="o">=</span> <span class="n">forms</span><span class="o">.</span><span class="n">CharField</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">default_data</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;name&#39;</span><span class="p">:</span> <span class="s1">&#39;Your name&#39;</span><span class="p">,</span> <span class="s1">&#39;url&#39;</span><span class="p">:</span> <span class="s1">&#39;http://&#39;</span><span class="p">}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span> <span class="o">=</span> <span class="n">CommentForm</span><span class="p">(</span><span class="n">default_data</span><span class="p">,</span> <span class="n">auto_id</span><span class="o">=</span><span class="kc">False</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">f</span><span class="p">)</span>
<span class="go">&lt;tr&gt;&lt;th&gt;Name:&lt;/th&gt;&lt;td&gt;&lt;input type=&quot;text&quot; name=&quot;name&quot; value=&quot;Your name&quot; required&gt;&lt;/td&gt;&lt;/tr&gt;</span>
<span class="go">&lt;tr&gt;&lt;th&gt;Url:&lt;/th&gt;&lt;td&gt;&lt;ul class=&quot;errorlist&quot;&gt;&lt;li&gt;Enter a valid URL.&lt;/li&gt;&lt;/ul&gt;&lt;input type=&quot;url&quot; name=&quot;url&quot; value=&quot;http://&quot; required&gt;&lt;/td&gt;&lt;/tr&gt;</span>
<span class="go">&lt;tr&gt;&lt;th&gt;Comment:&lt;/th&gt;&lt;td&gt;&lt;ul class=&quot;errorlist&quot;&gt;&lt;li&gt;This field is required.&lt;/li&gt;&lt;/ul&gt;&lt;input type=&quot;text&quot; name=&quot;comment&quot; required&gt;&lt;/td&gt;&lt;/tr&gt;</span>
</pre></div>
</div>
<p>这就是为什么 <code class="docutils literal notranslate"><span class="pre">initial</span></code> 值只在未绑定的表单中显示。对于绑定的表格，HTML 输出将使用绑定的数据。</p>
<p>还请注意，<code class="docutils literal notranslate"><span class="pre">initial</span></code> 值在验证中 <em>不</em> 用作“后备”数据，如果某个字段的值没有给出。<code class="docutils literal notranslate"><span class="pre">initial</span></code> 值 <em>仅</em> 用于初始表格显示：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">CommentForm</span><span class="p">(</span><span class="n">forms</span><span class="o">.</span><span class="n">Form</span><span class="p">):</span>
<span class="gp">... </span>    <span class="n">name</span> <span class="o">=</span> <span class="n">forms</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">initial</span><span class="o">=</span><span class="s1">&#39;Your name&#39;</span><span class="p">)</span>
<span class="gp">... </span>    <span class="n">url</span> <span class="o">=</span> <span class="n">forms</span><span class="o">.</span><span class="n">URLField</span><span class="p">(</span><span class="n">initial</span><span class="o">=</span><span class="s1">&#39;http://&#39;</span><span class="p">)</span>
<span class="gp">... </span>    <span class="n">comment</span> <span class="o">=</span> <span class="n">forms</span><span class="o">.</span><span class="n">CharField</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">data</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;name&#39;</span><span class="p">:</span> <span class="s1">&#39;&#39;</span><span class="p">,</span> <span class="s1">&#39;url&#39;</span><span class="p">:</span> <span class="s1">&#39;&#39;</span><span class="p">,</span> <span class="s1">&#39;comment&#39;</span><span class="p">:</span> <span class="s1">&#39;Foo&#39;</span><span class="p">}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span> <span class="o">=</span> <span class="n">CommentForm</span><span class="p">(</span><span class="n">data</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="o">.</span><span class="n">is_valid</span><span class="p">()</span>
<span class="go">False</span>
<span class="go"># The form does *not* fall back to using the initial values.</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="o">.</span><span class="n">errors</span>
<span class="go">{&#39;url&#39;: [&#39;This field is required.&#39;], &#39;name&#39;: [&#39;This field is required.&#39;]}</span>
</pre></div>
</div>
<p>你也可以通过任何可调用对象来代替常量。</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">datetime</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">DateForm</span><span class="p">(</span><span class="n">forms</span><span class="o">.</span><span class="n">Form</span><span class="p">):</span>
<span class="gp">... </span>    <span class="n">day</span> <span class="o">=</span> <span class="n">forms</span><span class="o">.</span><span class="n">DateField</span><span class="p">(</span><span class="n">initial</span><span class="o">=</span><span class="n">datetime</span><span class="o">.</span><span class="n">date</span><span class="o">.</span><span class="n">today</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">DateForm</span><span class="p">())</span>
<span class="go">&lt;tr&gt;&lt;th&gt;Day:&lt;/th&gt;&lt;td&gt;&lt;input type=&quot;text&quot; name=&quot;day&quot; value=&quot;12/23/2008&quot; required&gt;&lt;td&gt;&lt;/tr&gt;</span>
</pre></div>
</div>
<p>只有在显示未绑定的表单时，而不是在定义表单时，才会对可调用对象表单执行。</p>
</div>
<div class="section" id="s-widget">
<span id="widget"></span><h3><code class="docutils literal notranslate"><span class="pre">widget</span></code><a class="headerlink" href="#widget" title="永久链接至标题">¶</a></h3>
<dl class="attribute">
<dt id="django.forms.Field.widget">
<code class="descclassname">Field.</code><code class="descname">widget</code><a class="headerlink" href="#django.forms.Field.widget" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p><code class="docutils literal notranslate"><span class="pre">widget</span></code> 参数让你指定一个 <code class="docutils literal notranslate"><span class="pre">Widget</span></code> 类，以便在渲染这个 <code class="docutils literal notranslate"><span class="pre">Field</span></code> 时使用。参见 <a class="reference internal" href="widgets.html"><span class="doc">部件</span></a> 了解更多信息。</p>
</div>
<div class="section" id="s-help-text">
<span id="help-text"></span><h3><code class="docutils literal notranslate"><span class="pre">help_text</span></code><a class="headerlink" href="#help-text" title="永久链接至标题">¶</a></h3>
<dl class="attribute">
<dt id="django.forms.Field.help_text">
<code class="descclassname">Field.</code><code class="descname">help_text</code><a class="headerlink" href="#django.forms.Field.help_text" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p><code class="docutils literal notranslate"><span class="pre">help_text</span></code> 参数让你为这个 <code class="docutils literal notranslate"><span class="pre">Field</span></code> 指定描述性文本。如果你提供了 <code class="docutils literal notranslate"><span class="pre">help_text</span></code>，当 <code class="docutils literal notranslate"><span class="pre">Field</span></code> 被一个方便的 <code class="docutils literal notranslate"><span class="pre">Form</span></code> 方法（例如 <code class="docutils literal notranslate"><span class="pre">as_ul()</span></code>）渲染时，它将显示在 <code class="docutils literal notranslate"><span class="pre">Field`</span></code> 旁边。</p>
<p>就像模型字段的 <a class="reference internal" href="../models/fields.html#django.db.models.Field.help_text" title="django.db.models.Field.help_text"><code class="xref py py-attr docutils literal notranslate"><span class="pre">help_text</span></code></a> 一样，这个值在自动生成的表单中并没有被 HTML 封装。</p>
<p>这里是一个完整的例子 <code class="docutils literal notranslate"><span class="pre">Form</span></code>，它的两个字段实现了 <code class="docutils literal notranslate"><span class="pre">help_text</span></code>。我们指定 <code class="docutils literal notranslate"><span class="pre">auto_id=False</span></code> 以简化输出：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">django</span> <span class="kn">import</span> <span class="n">forms</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">HelpTextContactForm</span><span class="p">(</span><span class="n">forms</span><span class="o">.</span><span class="n">Form</span><span class="p">):</span>
<span class="gp">... </span>    <span class="n">subject</span> <span class="o">=</span> <span class="n">forms</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">100</span><span class="p">,</span> <span class="n">help_text</span><span class="o">=</span><span class="s1">&#39;100 characters max.&#39;</span><span class="p">)</span>
<span class="gp">... </span>    <span class="n">message</span> <span class="o">=</span> <span class="n">forms</span><span class="o">.</span><span class="n">CharField</span><span class="p">()</span>
<span class="gp">... </span>    <span class="n">sender</span> <span class="o">=</span> <span class="n">forms</span><span class="o">.</span><span class="n">EmailField</span><span class="p">(</span><span class="n">help_text</span><span class="o">=</span><span class="s1">&#39;A valid email address, please.&#39;</span><span class="p">)</span>
<span class="gp">... </span>    <span class="n">cc_myself</span> <span class="o">=</span> <span class="n">forms</span><span class="o">.</span><span class="n">BooleanField</span><span class="p">(</span><span class="n">required</span><span class="o">=</span><span class="kc">False</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span> <span class="o">=</span> <span class="n">HelpTextContactForm</span><span class="p">(</span><span class="n">auto_id</span><span class="o">=</span><span class="kc">False</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">f</span><span class="o">.</span><span class="n">as_table</span><span class="p">())</span>
<span class="go">&lt;tr&gt;&lt;th&gt;Subject:&lt;/th&gt;&lt;td&gt;&lt;input type=&quot;text&quot; name=&quot;subject&quot; maxlength=&quot;100&quot; required&gt;&lt;br&gt;&lt;span class=&quot;helptext&quot;&gt;100 characters max.&lt;/span&gt;&lt;/td&gt;&lt;/tr&gt;</span>
<span class="go">&lt;tr&gt;&lt;th&gt;Message:&lt;/th&gt;&lt;td&gt;&lt;input type=&quot;text&quot; name=&quot;message&quot; required&gt;&lt;/td&gt;&lt;/tr&gt;</span>
<span class="go">&lt;tr&gt;&lt;th&gt;Sender:&lt;/th&gt;&lt;td&gt;&lt;input type=&quot;email&quot; name=&quot;sender&quot; required&gt;&lt;br&gt;A valid email address, please.&lt;/td&gt;&lt;/tr&gt;</span>
<span class="go">&lt;tr&gt;&lt;th&gt;Cc myself:&lt;/th&gt;&lt;td&gt;&lt;input type=&quot;checkbox&quot; name=&quot;cc_myself&quot;&gt;&lt;/td&gt;&lt;/tr&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">f</span><span class="o">.</span><span class="n">as_ul</span><span class="p">()))</span>
<span class="go">&lt;li&gt;Subject: &lt;input type=&quot;text&quot; name=&quot;subject&quot; maxlength=&quot;100&quot; required&gt; &lt;span class=&quot;helptext&quot;&gt;100 characters max.&lt;/span&gt;&lt;/li&gt;</span>
<span class="go">&lt;li&gt;Message: &lt;input type=&quot;text&quot; name=&quot;message&quot; required&gt;&lt;/li&gt;</span>
<span class="go">&lt;li&gt;Sender: &lt;input type=&quot;email&quot; name=&quot;sender&quot; required&gt; A valid email address, please.&lt;/li&gt;</span>
<span class="go">&lt;li&gt;Cc myself: &lt;input type=&quot;checkbox&quot; name=&quot;cc_myself&quot;&gt;&lt;/li&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">f</span><span class="o">.</span><span class="n">as_p</span><span class="p">())</span>
<span class="go">&lt;p&gt;Subject: &lt;input type=&quot;text&quot; name=&quot;subject&quot; maxlength=&quot;100&quot; required&gt; &lt;span class=&quot;helptext&quot;&gt;100 characters max.&lt;/span&gt;&lt;/p&gt;</span>
<span class="go">&lt;p&gt;Message: &lt;input type=&quot;text&quot; name=&quot;message&quot; required&gt;&lt;/p&gt;</span>
<span class="go">&lt;p&gt;Sender: &lt;input type=&quot;email&quot; name=&quot;sender&quot; required&gt; A valid email address, please.&lt;/p&gt;</span>
<span class="go">&lt;p&gt;Cc myself: &lt;input type=&quot;checkbox&quot; name=&quot;cc_myself&quot;&gt;&lt;/p&gt;</span>
</pre></div>
</div>
</div>
<div class="section" id="s-error-messages">
<span id="error-messages"></span><h3><code class="docutils literal notranslate"><span class="pre">error_messages</span></code><a class="headerlink" href="#error-messages" title="永久链接至标题">¶</a></h3>
<dl class="attribute">
<dt id="django.forms.Field.error_messages">
<code class="descclassname">Field.</code><code class="descname">error_messages</code><a class="headerlink" href="#django.forms.Field.error_messages" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p><code class="docutils literal notranslate"><span class="pre">error_messages</span></code> 参数可以让你覆盖该字段将引发的默认消息。传递一个与你想覆盖的错误信息相匹配的键值的字典。例如，以下是默认的错误信息：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">django</span> <span class="kn">import</span> <span class="n">forms</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">generic</span> <span class="o">=</span> <span class="n">forms</span><span class="o">.</span><span class="n">CharField</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">generic</span><span class="o">.</span><span class="n">clean</span><span class="p">(</span><span class="s1">&#39;&#39;</span><span class="p">)</span>
<span class="gt">Traceback (most recent call last):</span>
  <span class="c">...</span>
<span class="gr">ValidationError</span>: <span class="n">[&#39;This field is required.&#39;]</span>
</pre></div>
</div>
<p>而这里是一个自定义的错误信息：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">name</span> <span class="o">=</span> <span class="n">forms</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">error_messages</span><span class="o">=</span><span class="p">{</span><span class="s1">&#39;required&#39;</span><span class="p">:</span> <span class="s1">&#39;Please enter your name&#39;</span><span class="p">})</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">name</span><span class="o">.</span><span class="n">clean</span><span class="p">(</span><span class="s1">&#39;&#39;</span><span class="p">)</span>
<span class="gt">Traceback (most recent call last):</span>
  <span class="c">...</span>
<span class="gr">ValidationError</span>: <span class="n">[&#39;Please enter your name&#39;]</span>
</pre></div>
</div>
<p>在下面的 <a class="reference internal" href="#built-in-field-classes">内置字段类</a> 一节中，每个 <code class="docutils literal notranslate"><span class="pre">Field</span></code> 定义了它所使用的错误信息键。</p>
</div>
<div class="section" id="s-validators">
<span id="validators"></span><h3><code class="docutils literal notranslate"><span class="pre">validators</span></code><a class="headerlink" href="#validators" title="永久链接至标题">¶</a></h3>
<dl class="attribute">
<dt id="django.forms.Field.validators">
<code class="descclassname">Field.</code><code class="descname">validators</code><a class="headerlink" href="#django.forms.Field.validators" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p><code class="docutils literal notranslate"><span class="pre">validators</span></code> 参数让你为这个字段提供一个验证函数列表。</p>
<p>更多信息请参见 <a class="reference internal" href="../validators.html"><span class="doc">验证器文档</span></a>。</p>
</div>
<div class="section" id="s-localize">
<span id="localize"></span><h3><code class="docutils literal notranslate"><span class="pre">localize</span></code><a class="headerlink" href="#localize" title="永久链接至标题">¶</a></h3>
<dl class="attribute">
<dt id="django.forms.Field.localize">
<code class="descclassname">Field.</code><code class="descname">localize</code><a class="headerlink" href="#django.forms.Field.localize" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p><code class="docutils literal notranslate"><span class="pre">localize</span></code> 参数可以实现表单数据输入和渲染输出的本地化。</p>
<p>更多信息请参见 <a class="reference internal" href="../../topics/i18n/formatting.html"><span class="doc">格式本地化</span></a> 文档。</p>
</div>
<div class="section" id="s-disabled">
<span id="disabled"></span><h3><code class="docutils literal notranslate"><span class="pre">disabled</span></code><a class="headerlink" href="#disabled" title="永久链接至标题">¶</a></h3>
<dl class="attribute">
<dt id="django.forms.Field.disabled">
<code class="descclassname">Field.</code><code class="descname">disabled</code><a class="headerlink" href="#django.forms.Field.disabled" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p><code class="docutils literal notranslate"><span class="pre">disabled</span></code> 布尔参数设置为 <code class="docutils literal notranslate"><span class="pre">True</span></code> 时，使用 <code class="docutils literal notranslate"><span class="pre">disabled</span></code> HTML 属性禁用表单字段，使其不能被用户编辑。即使用户篡改了提交给服务器的字段值，也会被忽略，而采用表单初始数据的值。</p>
</div>
</div>
<div class="section" id="s-checking-if-the-field-data-has-changed">
<span id="checking-if-the-field-data-has-changed"></span><h2>检查字段数据是否有变化<a class="headerlink" href="#checking-if-the-field-data-has-changed" title="永久链接至标题">¶</a></h2>
<div class="section" id="s-has-changed">
<span id="has-changed"></span><h3><code class="docutils literal notranslate"><span class="pre">has_changed()</span></code><a class="headerlink" href="#has-changed" title="永久链接至标题">¶</a></h3>
<dl class="method">
<dt id="django.forms.Field.has_changed">
<code class="descclassname">Field.</code><code class="descname">has_changed</code>()<a class="headerlink" href="#django.forms.Field.has_changed" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p><code class="docutils literal notranslate"><span class="pre">has_changed()</span></code> 方法用于确定字段值是否与初始值发生了变化。返回 <code class="docutils literal notranslate"><span class="pre">True</span></code> 或 <code class="docutils literal notranslate"><span class="pre">False</span></code>。</p>
<p>更多信息请参见 <a class="reference internal" href="api.html#django.forms.Form.has_changed" title="django.forms.Form.has_changed"><code class="xref py py-class docutils literal notranslate"><span class="pre">Form.has_changed()</span></code></a> 文档。</p>
</div>
</div>
<div class="section" id="s-built-in-field-classes">
<span id="s-built-in-fields"></span><span id="built-in-field-classes"></span><span id="built-in-fields"></span><h2>内置 <code class="docutils literal notranslate"><span class="pre">Field</span></code> 类<a class="headerlink" href="#built-in-field-classes" title="永久链接至标题">¶</a></h2>
<p>当然，<code class="docutils literal notranslate"><span class="pre">forms</span></code> 库附带了一组 <code class="docutils literal notranslate"><span class="pre">Field</span></code> 类，代表了常见的验证需求。本节将对每个内置字段进行说明。</p>
<p>对于每个字段，我们描述了在你没有指定 <code class="docutils literal notranslate"><span class="pre">widget</span></code> 时使用的默认部件。我们还指定了当你提供一个空值时返回的值（参见上文 <code class="docutils literal notranslate"><span class="pre">required</span></code> 一节以了解其含义）。</p>
<div class="section" id="s-booleanfield">
<span id="booleanfield"></span><h3><code class="docutils literal notranslate"><span class="pre">BooleanField</span></code><a class="headerlink" href="#booleanfield" title="永久链接至标题">¶</a></h3>
<dl class="class">
<dt id="django.forms.BooleanField">
<em class="property">class </em><code class="descname">BooleanField</code>(<em>**kwargs</em>)<a class="headerlink" href="#django.forms.BooleanField" title="永久链接至目标">¶</a></dt>
<dd><ul class="simple">
<li>默认部件：<a class="reference internal" href="widgets.html#django.forms.CheckboxInput" title="django.forms.CheckboxInput"><code class="xref py py-class docutils literal notranslate"><span class="pre">CheckboxInput</span></code></a></li>
<li>空值：<code class="docutils literal notranslate"><span class="pre">False</span></code></li>
<li>规范化为：Python 的 <code class="docutils literal notranslate"><span class="pre">True</span></code> 或 <code class="docutils literal notranslate"><span class="pre">False</span></code> 值。</li>
<li>如果字段有 <code class="docutils literal notranslate"><span class="pre">required=True</span></code>，则验证该值是否为 <code class="docutils literal notranslate"><span class="pre">True</span></code> （例如，复选框被选中）。</li>
<li>错误信息键：<code class="docutils literal notranslate"><span class="pre">required</span></code></li>
</ul>
<div class="admonition note">
<p class="first admonition-title">注解</p>
<p class="last">由于所有 <code class="docutils literal notranslate"><span class="pre">Field</span></code> 子类默认都有 <code class="docutils literal notranslate"><span class="pre">required=True</span></code>，这里的验证条件很重要。如果你想在你的表单中包含一个布尔值，这个布尔值可以是 <code class="docutils literal notranslate"><span class="pre">True</span></code> 或 <code class="docutils literal notranslate"><span class="pre">False</span></code> （例如一个选中或未选中的复选框），你必须记得在创建 <code class="docutils literal notranslate"><span class="pre">BooleanField</span></code> 时传递 <code class="docutils literal notranslate"><span class="pre">required=False</span></code>。</p>
</div>
</dd></dl>

</div>
<div class="section" id="s-charfield">
<span id="charfield"></span><h3><code class="docutils literal notranslate"><span class="pre">CharField</span></code><a class="headerlink" href="#charfield" title="永久链接至标题">¶</a></h3>
<dl class="class">
<dt id="django.forms.CharField">
<em class="property">class </em><code class="descname">CharField</code>(<em>**kwargs</em>)<a class="headerlink" href="#django.forms.CharField" title="永久链接至目标">¶</a></dt>
<dd><ul class="simple">
<li>默认部件：<a class="reference internal" href="widgets.html#django.forms.TextInput" title="django.forms.TextInput"><code class="xref py py-class docutils literal notranslate"><span class="pre">TextInput</span></code></a></li>
<li>空值：不管你给 <a class="reference internal" href="#django.forms.CharField.empty_value" title="django.forms.CharField.empty_value"><code class="xref py py-attr docutils literal notranslate"><span class="pre">empty_value</span></code></a> 的是什么。</li>
<li>规范化为：一个字符串。</li>
<li>如果提供了 <code class="docutils literal notranslate"><span class="pre">max_length</span></code> 和 <code class="docutils literal notranslate"><span class="pre">min_length</span></code>，则使用 <a class="reference internal" href="../validators.html#django.core.validators.MaxLengthValidator" title="django.core.validators.MaxLengthValidator"><code class="xref py py-class docutils literal notranslate"><span class="pre">MaxLengthValidator</span></code></a> 和 <a class="reference internal" href="../validators.html#django.core.validators.MinLengthValidator" title="django.core.validators.MinLengthValidator"><code class="xref py py-class docutils literal notranslate"><span class="pre">MinLengthValidator</span></code></a>。否则，所有输入都有效。</li>
<li>错误信息键：<code class="docutils literal notranslate"><span class="pre">required</span></code>、<code class="docutils literal notranslate"><span class="pre">max_length</span></code>、<code class="docutils literal notranslate"><span class="pre">min_length</span></code></li>
</ul>
<p>需要四个可选参数进行验证：</p>
<dl class="attribute">
<dt id="django.forms.CharField.max_length">
<code class="descname">max_length</code><a class="headerlink" href="#django.forms.CharField.max_length" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<dl class="attribute">
<dt id="django.forms.CharField.min_length">
<code class="descname">min_length</code><a class="headerlink" href="#django.forms.CharField.min_length" title="永久链接至目标">¶</a></dt>
<dd><p>如果提供了这些参数，这些参数确保字符串的长度最多或至少是给定的长度。</p>
</dd></dl>

<dl class="attribute">
<dt id="django.forms.CharField.strip">
<code class="descname">strip</code><a class="headerlink" href="#django.forms.CharField.strip" title="永久链接至目标">¶</a></dt>
<dd><p>如果 <code class="docutils literal notranslate"><span class="pre">True</span></code> （默认），该值将被去掉前导和尾部的空白。</p>
</dd></dl>

<dl class="attribute">
<dt id="django.forms.CharField.empty_value">
<code class="descname">empty_value</code><a class="headerlink" href="#django.forms.CharField.empty_value" title="永久链接至目标">¶</a></dt>
<dd><p>用来表示“空”的值。默认为空字符串。</p>
</dd></dl>

</dd></dl>

</div>
<div class="section" id="s-choicefield">
<span id="choicefield"></span><h3><code class="docutils literal notranslate"><span class="pre">ChoiceField</span></code><a class="headerlink" href="#choicefield" title="永久链接至标题">¶</a></h3>
<dl class="class">
<dt id="django.forms.ChoiceField">
<em class="property">class </em><code class="descname">ChoiceField</code>(<em>**kwargs</em>)<a class="headerlink" href="#django.forms.ChoiceField" title="永久链接至目标">¶</a></dt>
<dd><ul class="simple">
<li>默认部件：<a class="reference internal" href="widgets.html#django.forms.Select" title="django.forms.Select"><code class="xref py py-class docutils literal notranslate"><span class="pre">Select</span></code></a></li>
<li>空值：<code class="docutils literal notranslate"><span class="pre">''</span></code> （空字符串）</li>
<li>规范化为：一个字符串。</li>
<li>验证给定值是否存在于选择列表中。</li>
<li>错误信息键：<code class="docutils literal notranslate"><span class="pre">required</span></code>、<code class="docutils literal notranslate"><span class="pre">invalid_choice</span></code></li>
</ul>
<p><code class="docutils literal notranslate"><span class="pre">invalid_choice</span></code> 错误信息可能包含 <code class="docutils literal notranslate"><span class="pre">%(value)s</span></code>，该信息将被替换为选定的选择。</p>
<p>需要一个额外的参数：</p>
<dl class="attribute">
<dt id="django.forms.ChoiceField.choices">
<code class="descname">choices</code><a class="headerlink" href="#django.forms.ChoiceField.choices" title="永久链接至目标">¶</a></dt>
<dd><p>或者是一个 <a class="reference external" href="https://docs.python.org/3/glossary.html#term-iterable" title="(在 Python v3.10)"><span class="xref std std-term">iterable</span></a> 的二元元组作为这个字段的选择，或者是一个 <a class="reference internal" href="../models/fields.html#field-choices-enum-types"><span class="std std-ref">enumeration</span></a> 的选择，或者是一个返回这样一个迭代器的可调用对象。这个参数接受的格式与模型字段的 <code class="docutils literal notranslate"><span class="pre">choices</span></code> 参数相同。更多细节请参见 <a class="reference internal" href="../models/fields.html#field-choices"><span class="std std-ref">模型字段引用文档中的选择</span></a>。如果这个参数是可调用的，那么除了在渲染过程中，每次初始化字段的表单时，它都会被执行。默认为空列表。</p>
</dd></dl>

</dd></dl>

</div>
<div class="section" id="s-typedchoicefield">
<span id="typedchoicefield"></span><h3><code class="docutils literal notranslate"><span class="pre">TypedChoiceField</span></code><a class="headerlink" href="#typedchoicefield" title="永久链接至标题">¶</a></h3>
<dl class="class">
<dt id="django.forms.TypedChoiceField">
<em class="property">class </em><code class="descname">TypedChoiceField</code>(<em>**kwargs</em>)<a class="headerlink" href="#django.forms.TypedChoiceField" title="永久链接至目标">¶</a></dt>
<dd><p>就像 <a class="reference internal" href="#django.forms.ChoiceField" title="django.forms.ChoiceField"><code class="xref py py-class docutils literal notranslate"><span class="pre">ChoiceField</span></code></a> 一样，除了 <a class="reference internal" href="#django.forms.TypedChoiceField" title="django.forms.TypedChoiceField"><code class="xref py py-class docutils literal notranslate"><span class="pre">TypedChoiceField</span></code></a> 需要两个额外的参数 <a class="reference internal" href="#django.forms.TypedChoiceField.coerce" title="django.forms.TypedChoiceField.coerce"><code class="xref py py-attr docutils literal notranslate"><span class="pre">coerce</span></code></a> 和 <a class="reference internal" href="#django.forms.TypedChoiceField.empty_value" title="django.forms.TypedChoiceField.empty_value"><code class="xref py py-attr docutils literal notranslate"><span class="pre">empty_value</span></code></a>。</p>
<ul class="simple">
<li>默认部件：<a class="reference internal" href="widgets.html#django.forms.Select" title="django.forms.Select"><code class="xref py py-class docutils literal notranslate"><span class="pre">Select</span></code></a></li>
<li>空值：不管你给 <a class="reference internal" href="#django.forms.TypedChoiceField.empty_value" title="django.forms.TypedChoiceField.empty_value"><code class="xref py py-attr docutils literal notranslate"><span class="pre">empty_value</span></code></a> 的是什么。</li>
<li>规范化为：<a class="reference internal" href="#django.forms.TypedChoiceField.coerce" title="django.forms.TypedChoiceField.coerce"><code class="xref py py-attr docutils literal notranslate"><span class="pre">coerce</span></code></a> 参数提供的类型的值。</li>
<li>验证给定的值是否存在于选择列表中，并且可以被强制执行。</li>
<li>错误信息键：<code class="docutils literal notranslate"><span class="pre">required</span></code>、<code class="docutils literal notranslate"><span class="pre">invalid_choice</span></code></li>
</ul>
<p>需要额外的参数：</p>
<dl class="attribute">
<dt id="django.forms.TypedChoiceField.coerce">
<code class="descname">coerce</code><a class="headerlink" href="#django.forms.TypedChoiceField.coerce" title="永久链接至目标">¶</a></dt>
<dd><p>接受一个参数并返回一个强制值的函数。例子包括内置的 <code class="docutils literal notranslate"><span class="pre">int</span></code>、<code class="docutils literal notranslate"><span class="pre">float</span></code>、<code class="docutils literal notranslate"><span class="pre">bool</span></code> 和其他类型。默认为身份函数。请注意，强制执行发生在输入验证之后，所以可以强制执行到一个不存在于``choices``中的值。</p>
</dd></dl>

<dl class="attribute">
<dt id="django.forms.TypedChoiceField.empty_value">
<code class="descname">empty_value</code><a class="headerlink" href="#django.forms.TypedChoiceField.empty_value" title="永久链接至目标">¶</a></dt>
<dd><p>用来表示“空”的值。默认为空字符串；<code class="docutils literal notranslate"><span class="pre">None</span></code> 是另一种常见的选择。请注意，这个值不会被 <code class="docutils literal notranslate"><span class="pre">coerce</span></code> 参数中给出的函数强制执行，所以要据此选择。</p>
</dd></dl>

</dd></dl>

</div>
<div class="section" id="s-datefield">
<span id="datefield"></span><h3><code class="docutils literal notranslate"><span class="pre">DateField</span></code><a class="headerlink" href="#datefield" title="永久链接至标题">¶</a></h3>
<dl class="class">
<dt id="django.forms.DateField">
<em class="property">class </em><code class="descname">DateField</code>(<em>**kwargs</em>)<a class="headerlink" href="#django.forms.DateField" title="永久链接至目标">¶</a></dt>
<dd><ul class="simple">
<li>默认部件：<a class="reference internal" href="widgets.html#django.forms.DateInput" title="django.forms.DateInput"><code class="xref py py-class docutils literal notranslate"><span class="pre">DateInput</span></code></a></li>
<li>空值：<code class="docutils literal notranslate"><span class="pre">None</span></code></li>
<li>规范化为：Python 的 <code class="docutils literal notranslate"><span class="pre">datetime.date</span></code> 对象。</li>
<li>验证给定值是 <code class="docutils literal notranslate"><span class="pre">datetime.date</span></code>、<code class="docutils literal notranslate"><span class="pre">datetime.datetime</span></code> 或以特定日期格式化的字符串。</li>
<li>错误信息键：<code class="docutils literal notranslate"><span class="pre">required</span></code>、<code class="docutils literal notranslate"><span class="pre">invalid</span></code></li>
</ul>
<p>需要一个可选的参数：</p>
<dl class="attribute">
<dt id="django.forms.DateField.input_formats">
<code class="descname">input_formats</code><a class="headerlink" href="#django.forms.DateField.input_formats" title="永久链接至目标">¶</a></dt>
<dd><p>用于将字符串转换为有效的 <code class="docutils literal notranslate"><span class="pre">datetime.date</span></code> 对象的格式列表。</p>
</dd></dl>

<p>如果没有提供 <code class="docutils literal notranslate"><span class="pre">input_formats</span></code> 参数，如果 <a class="reference internal" href="../settings.html#std:setting-USE_L10N"><code class="xref std std-setting docutils literal notranslate"><span class="pre">USE_L10N</span></code></a> 为 <code class="docutils literal notranslate"><span class="pre">False</span></code>，则默认输入格式来自 <a class="reference internal" href="../settings.html#std:setting-DATE_INPUT_FORMATS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">DATE_INPUT_FORMATS</span></code></a>，如果启用了本地化，则默认输入格式来自激活的的本地格式 <code class="docutils literal notranslate"><span class="pre">DATE_INPUT_FORMATS</span></code> 键。也请参见 <a class="reference internal" href="../../topics/i18n/formatting.html"><span class="doc">格式本地化</span></a>。</p>
</dd></dl>

</div>
<div class="section" id="s-datetimefield">
<span id="datetimefield"></span><h3><code class="docutils literal notranslate"><span class="pre">DateTimeField</span></code><a class="headerlink" href="#datetimefield" title="永久链接至标题">¶</a></h3>
<dl class="class">
<dt id="django.forms.DateTimeField">
<em class="property">class </em><code class="descname">DateTimeField</code>(<em>**kwargs</em>)<a class="headerlink" href="#django.forms.DateTimeField" title="永久链接至目标">¶</a></dt>
<dd><ul class="simple">
<li>默认部件：<a class="reference internal" href="widgets.html#django.forms.DateTimeInput" title="django.forms.DateTimeInput"><code class="xref py py-class docutils literal notranslate"><span class="pre">DateTimeInput</span></code></a></li>
<li>空值：<code class="docutils literal notranslate"><span class="pre">None</span></code></li>
<li>规范化为：Python 的 <code class="docutils literal notranslate"><span class="pre">datetime.datetime</span></code> 对象。</li>
<li>验证给定的值是 <code class="docutils literal notranslate"><span class="pre">datetime.datetime</span></code>、<code class="docutils literal notranslate"><span class="pre">datetime.date</span></code> 或以特定日期时间格式化的字符串。</li>
<li>错误信息键：<code class="docutils literal notranslate"><span class="pre">required</span></code>、<code class="docutils literal notranslate"><span class="pre">invalid</span></code></li>
</ul>
<p>需要一个可选的参数：</p>
<dl class="attribute">
<dt id="django.forms.DateTimeField.input_formats">
<code class="descname">input_formats</code><a class="headerlink" href="#django.forms.DateTimeField.input_formats" title="永久链接至目标">¶</a></dt>
<dd><p>除 ISO 8601 格式外，还列出了用于将字符串转换为有效的 <code class="docutils literal notranslate"><span class="pre">datetime.datetime</span></code> 对象的格式。</p>
</dd></dl>

<p>该字段总是接受 ISO 8601 格式的日期或类似的 <a class="reference internal" href="../utils.html#django.utils.dateparse.parse_datetime" title="django.utils.dateparse.parse_datetime"><code class="xref py py-func docutils literal notranslate"><span class="pre">parse_datetime()</span></code></a> 识别的字符串。一些例子是：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="o">*</span> <span class="s1">&#39;2006-10-25 14:30:59&#39;</span>
<span class="o">*</span> <span class="s1">&#39;2006-10-25T14:30:59&#39;</span>
<span class="o">*</span> <span class="s1">&#39;2006-10-25 14:30&#39;</span>
<span class="o">*</span> <span class="s1">&#39;2006-10-25T14:30&#39;</span>
<span class="o">*</span> <span class="s1">&#39;2006-10-25T14:30Z&#39;</span>
<span class="o">*</span> <span class="s1">&#39;2006-10-25T14:30+02:00&#39;</span>
<span class="o">*</span> <span class="s1">&#39;2006-10-25&#39;</span>
</pre></div>
</div>
<p>如果没有提供 <code class="docutils literal notranslate"><span class="pre">input_formats</span></code> 参数，默认的输入格式来自 <a class="reference internal" href="../settings.html#std:setting-DATETIME_INPUT_FORMATS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">DATETIME_INPUT_FORMATS</span></code></a> 和 <a class="reference internal" href="../settings.html#std:setting-DATE_INPUT_FORMATS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">DATE_INPUT_FORMATS</span></code></a>，如果: setting:<cite>USE_L10N</cite> 为 <code class="docutils literal notranslate"><span class="pre">False</span></code>，如果启用了本地化，则从激活的本地格式 <code class="docutils literal notranslate"><span class="pre">DATETIME_INPUT_FORMATS</span></code> 和 <code class="docutils literal notranslate"><span class="pre">DATE_INPUT_FORMATS</span></code> 键中获取。也请参见 <a class="reference internal" href="../../topics/i18n/formatting.html"><span class="doc">格式本地化</span></a>。</p>
<div class="versionchanged">
<span class="title">Changed in Django 3.1:</span> <p>增加了对 ISO 8601 日期字符串解析的支持（包括可选的时区）。</p>
<p>在默认的 <code class="docutils literal notranslate"><span class="pre">input_formats</span></code> 中增加了 <code class="docutils literal notranslate"><span class="pre">DATE_INPUT_FORMATS</span></code> 的后备功能。</p>
</div>
</dd></dl>

</div>
<div class="section" id="s-decimalfield">
<span id="decimalfield"></span><h3><code class="docutils literal notranslate"><span class="pre">DecimalField</span></code><a class="headerlink" href="#decimalfield" title="永久链接至标题">¶</a></h3>
<dl class="class">
<dt id="django.forms.DecimalField">
<em class="property">class </em><code class="descname">DecimalField</code>(<em>**kwargs</em>)<a class="headerlink" href="#django.forms.DecimalField" title="永久链接至目标">¶</a></dt>
<dd><ul class="simple">
<li>当 <a class="reference internal" href="#django.forms.Field.localize" title="django.forms.Field.localize"><code class="xref py py-attr docutils literal notranslate"><span class="pre">Field.localize</span></code></a> 为 <code class="docutils literal notranslate"><span class="pre">False</span></code> 时是 <a class="reference internal" href="widgets.html#django.forms.NumberInput" title="django.forms.NumberInput"><code class="xref py py-class docutils literal notranslate"><span class="pre">NumberInput</span></code></a> 否则，该字段的默认表单部件是 <a class="reference internal" href="widgets.html#django.forms.TextInput" title="django.forms.TextInput"><code class="xref py py-class docutils literal notranslate"><span class="pre">TextInput</span></code></a>。</li>
<li>空值：<code class="docutils literal notranslate"><span class="pre">None</span></code></li>
<li>规范化为：Python 的 <code class="docutils literal notranslate"><span class="pre">decimal</span></code>。</li>
<li>验证给定值是否为十进制。如果提供了 <code class="docutils literal notranslate"><span class="pre">max_value</span></code> 和 <code class="docutils literal notranslate"><span class="pre">min_value</span></code>，则使用 <a class="reference internal" href="../validators.html#django.core.validators.MaxValueValidator" title="django.core.validators.MaxValueValidator"><code class="xref py py-class docutils literal notranslate"><span class="pre">MaxValueValidator</span></code></a> 和 <a class="reference internal" href="../validators.html#django.core.validators.MinValueValidator" title="django.core.validators.MinValueValidator"><code class="xref py py-class docutils literal notranslate"><span class="pre">MinValueValidator</span></code></a>。前面和后面的空格会被忽略。</li>
<li>错误信息键：<code class="docutils literal notranslate"><span class="pre">required</span></code>、<code class="docutils literal notranslate"><span class="pre">invalid</span></code>、<code class="docutils literal notranslate"><span class="pre">max_value</span></code>、<code class="docutils literal notranslate"><span class="pre">min_value</span></code>、<code class="docutils literal notranslate"><span class="pre">max_digits</span></code>、<code class="docutils literal notranslate"><span class="pre">max_decimal_places</span></code>、<code class="docutils literal notranslate"><span class="pre">max_whole_digits</span></code></li>
</ul>
<p><code class="docutils literal notranslate"><span class="pre">max_value</span></code> 和 <code class="docutils literal notranslate"><span class="pre">min_value</span></code> 错误信息可能包含 <code class="docutils literal notranslate"><span class="pre">%(limit_value)s</span></code>，将用适当的限制代替。同样，<code class="docutils literal notranslate"><span class="pre">max_digits</span></code>、<code class="docutils literal notranslate"><span class="pre">max_decimal_places</span></code> 和 <code class="docutils literal notranslate"><span class="pre">max_whole_digits</span></code> 错误信息可能包含 <code class="docutils literal notranslate"><span class="pre">%(max)s</span></code>。</p>
<p>需要四个可选的参数：</p>
<dl class="attribute">
<dt id="django.forms.DecimalField.max_value">
<code class="descname">max_value</code><a class="headerlink" href="#django.forms.DecimalField.max_value" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<dl class="attribute">
<dt id="django.forms.DecimalField.min_value">
<code class="descname">min_value</code><a class="headerlink" href="#django.forms.DecimalField.min_value" title="永久链接至目标">¶</a></dt>
<dd><p>这些控制着字段中允许的数值范围，应以 <code class="docutils literal notranslate"><span class="pre">decimal.Decimal</span></code> 值的形式给出。</p>
</dd></dl>

<dl class="attribute">
<dt id="django.forms.DecimalField.max_digits">
<code class="descname">max_digits</code><a class="headerlink" href="#django.forms.DecimalField.max_digits" title="永久链接至目标">¶</a></dt>
<dd><p>值中允许的最大数字（小数点前的数字加上小数点后的数字，去掉前导零）。</p>
</dd></dl>

<dl class="attribute">
<dt id="django.forms.DecimalField.decimal_places">
<code class="descname">decimal_places</code><a class="headerlink" href="#django.forms.DecimalField.decimal_places" title="永久链接至目标">¶</a></dt>
<dd><p>允许的最大小数位数。</p>
</dd></dl>

</dd></dl>

</div>
<div class="section" id="s-durationfield">
<span id="durationfield"></span><h3><code class="docutils literal notranslate"><span class="pre">DurationField</span></code><a class="headerlink" href="#durationfield" title="永久链接至标题">¶</a></h3>
<dl class="class">
<dt id="django.forms.DurationField">
<em class="property">class </em><code class="descname">DurationField</code>(<em>**kwargs</em>)<a class="headerlink" href="#django.forms.DurationField" title="永久链接至目标">¶</a></dt>
<dd><ul class="simple">
<li>默认部件：<a class="reference internal" href="widgets.html#django.forms.TextInput" title="django.forms.TextInput"><code class="xref py py-class docutils literal notranslate"><span class="pre">TextInput</span></code></a></li>
<li>空值：<code class="docutils literal notranslate"><span class="pre">None</span></code></li>
<li>规范化为：Python 的 <a class="reference external" href="https://docs.python.org/3/library/datetime.html#datetime.timedelta" title="(在 Python v3.10)"><code class="xref py py-class docutils literal notranslate"><span class="pre">timedelta</span></code></a>。</li>
<li>验证给定值是否是一个字符串，可以转换成 <code class="docutils literal notranslate"><span class="pre">timedelta</span></code>。该值必须在 <a class="reference external" href="https://docs.python.org/3/library/datetime.html#datetime.timedelta.min" title="(在 Python v3.10)"><code class="xref py py-attr docutils literal notranslate"><span class="pre">datetime.timedelta.min</span></code></a> 和 <a class="reference external" href="https://docs.python.org/3/library/datetime.html#datetime.timedelta.max" title="(在 Python v3.10)"><code class="xref py py-attr docutils literal notranslate"><span class="pre">datetime.timedelta.max</span></code></a> 之间。</li>
<li>错误信息键：<code class="docutils literal notranslate"><span class="pre">required</span></code>、<code class="docutils literal notranslate"><span class="pre">invalid</span></code>、<code class="docutils literal notranslate"><span class="pre">overflow</span></code></li>
</ul>
<p>接受 <a class="reference internal" href="../utils.html#django.utils.dateparse.parse_duration" title="django.utils.dateparse.parse_duration"><code class="xref py py-func docutils literal notranslate"><span class="pre">parse_duration()</span></code></a> 理解的任何格式。</p>
</dd></dl>

</div>
<div class="section" id="s-emailfield">
<span id="emailfield"></span><h3><code class="docutils literal notranslate"><span class="pre">EmailField</span></code><a class="headerlink" href="#emailfield" title="永久链接至标题">¶</a></h3>
<dl class="class">
<dt id="django.forms.EmailField">
<em class="property">class </em><code class="descname">EmailField</code>(<em>**kwargs</em>)<a class="headerlink" href="#django.forms.EmailField" title="永久链接至目标">¶</a></dt>
<dd><ul class="simple">
<li>默认部件：<a class="reference internal" href="widgets.html#django.forms.EmailInput" title="django.forms.EmailInput"><code class="xref py py-class docutils literal notranslate"><span class="pre">EmailInput</span></code></a></li>
<li>空值：不管你给 <code class="xref py py-attr docutils literal notranslate"><span class="pre">empty_value</span></code> 的是什么。</li>
<li>规范化为：一个字符串。</li>
<li>使用 <a class="reference internal" href="../validators.html#django.core.validators.EmailValidator" title="django.core.validators.EmailValidator"><code class="xref py py-class docutils literal notranslate"><span class="pre">EmailValidator</span></code></a> 来验证给定的值是一个有效的电子邮件地址，使用一个适度复杂的正则表达式。</li>
<li>错误信息键：<code class="docutils literal notranslate"><span class="pre">required</span></code>、<code class="docutils literal notranslate"><span class="pre">invalid</span></code></li>
</ul>
<p>有三个可选参数 <code class="docutils literal notranslate"><span class="pre">max_length</span></code>、<code class="docutils literal notranslate"><span class="pre">min_length</span></code> 和 <code class="docutils literal notranslate"><span class="pre">empty_value</span></code>，它们的工作原理与 <a class="reference internal" href="#django.forms.CharField" title="django.forms.CharField"><code class="xref py py-class docutils literal notranslate"><span class="pre">CharField</span></code></a> 一样。</p>
</dd></dl>

</div>
<div class="section" id="s-filefield">
<span id="filefield"></span><h3><code class="docutils literal notranslate"><span class="pre">FileField</span></code><a class="headerlink" href="#filefield" title="永久链接至标题">¶</a></h3>
<dl class="class">
<dt id="django.forms.FileField">
<em class="property">class </em><code class="descname">FileField</code>(<em>**kwargs</em>)<a class="headerlink" href="#django.forms.FileField" title="永久链接至目标">¶</a></dt>
<dd><ul class="simple">
<li>默认部件：<a class="reference internal" href="widgets.html#django.forms.ClearableFileInput" title="django.forms.ClearableFileInput"><code class="xref py py-class docutils literal notranslate"><span class="pre">ClearableFileInput</span></code></a></li>
<li>空值：<code class="docutils literal notranslate"><span class="pre">None</span></code></li>
<li>规范化为：一个 <code class="docutils literal notranslate"><span class="pre">UploadedFile</span></code> 对象，它将文件内容和文件名包装成一个单一对象。</li>
<li>可以验证非空文件数据已经绑定到表单中。</li>
<li>错误信息键：<code class="docutils literal notranslate"><span class="pre">required</span></code>、<code class="docutils literal notranslate"><span class="pre">invalid</span></code>、<code class="docutils literal notranslate"><span class="pre">missing</span></code>、<code class="docutils literal notranslate"><span class="pre">empty</span></code>、<code class="docutils literal notranslate"><span class="pre">max_length</span></code></li>
</ul>
<p>有两个可选的验证参数，<code class="docutils literal notranslate"><span class="pre">max_length</span></code> 和 <code class="docutils literal notranslate"><span class="pre">allow_empty_file</span></code>。如果提供了这两个参数，将确保文件名的长度最多为给定长度，即使文件内容为空，验证也会成功。</p>
<p>要了解更多关于 <code class="docutils literal notranslate"><span class="pre">UploadedFile</span></code> 对象的信息，请看 <a class="reference internal" href="../../topics/http/file-uploads.html"><span class="doc">文件上传文档</span></a>。</p>
<p>当你在表单中使用 <code class="docutils literal notranslate"><span class="pre">FileField</span></code> 时，你还必须记住 <a class="reference internal" href="api.html#binding-uploaded-files"><span class="std std-ref">将文件数据绑定到表单中</span></a>。</p>
<p><code class="docutils literal notranslate"><span class="pre">max_length</span></code> 错误指的是文件名的长度。在该键的错误信息中，<code class="docutils literal notranslate"><span class="pre">%(max)d</span></code> 将被替换为最大文件名长度，<code class="docutils literal notranslate"><span class="pre">%(length)d</span></code> 将被替换为当前文件名长度。</p>
</dd></dl>

</div>
<div class="section" id="s-filepathfield">
<span id="filepathfield"></span><h3><code class="docutils literal notranslate"><span class="pre">FilePathField</span></code><a class="headerlink" href="#filepathfield" title="永久链接至标题">¶</a></h3>
<dl class="class">
<dt id="django.forms.FilePathField">
<em class="property">class </em><code class="descname">FilePathField</code>(<em>**kwargs</em>)<a class="headerlink" href="#django.forms.FilePathField" title="永久链接至目标">¶</a></dt>
<dd><ul class="simple">
<li>默认部件：<a class="reference internal" href="widgets.html#django.forms.Select" title="django.forms.Select"><code class="xref py py-class docutils literal notranslate"><span class="pre">Select</span></code></a></li>
<li>空值：<code class="docutils literal notranslate"><span class="pre">''</span></code> （空字符串）</li>
<li>规范化为：一个字符串。</li>
<li>验证选择是否存在于选择列表中。</li>
<li>错误信息键：<code class="docutils literal notranslate"><span class="pre">required</span></code>、<code class="docutils literal notranslate"><span class="pre">invalid_choice</span></code></li>
</ul>
<p>该字段允许从某个目录内的文件中选择。它需要五个额外的参数；只有 <code class="docutils literal notranslate"><span class="pre">path</span></code> 是必须的。</p>
<dl class="attribute">
<dt id="django.forms.FilePathField.path">
<code class="descname">path</code><a class="headerlink" href="#django.forms.FilePathField.path" title="永久链接至目标">¶</a></dt>
<dd><p>你想要列出的内容的目录的绝对路径。该目录必须存在。</p>
</dd></dl>

<dl class="attribute">
<dt id="django.forms.FilePathField.recursive">
<code class="descname">recursive</code><a class="headerlink" href="#django.forms.FilePathField.recursive" title="永久链接至目标">¶</a></dt>
<dd><p>如果 <code class="docutils literal notranslate"><span class="pre">False</span></code> （默认），只提供 <code class="docutils literal notranslate"><span class="pre">path</span></code> 的直接内容作为选择。如果 <code class="docutils literal notranslate"><span class="pre">True</span></code>，目录将被递归递进，所有的子目录将被列为选择。</p>
</dd></dl>

<dl class="attribute">
<dt id="django.forms.FilePathField.match">
<code class="descname">match</code><a class="headerlink" href="#django.forms.FilePathField.match" title="永久链接至目标">¶</a></dt>
<dd><p>正则表达式模式；只允许将名称与此表达式相匹配的文件作为选择。</p>
</dd></dl>

<dl class="attribute">
<dt id="django.forms.FilePathField.allow_files">
<code class="descname">allow_files</code><a class="headerlink" href="#django.forms.FilePathField.allow_files" title="永久链接至目标">¶</a></dt>
<dd><p>可选。 可选 <code class="docutils literal notranslate"><span class="pre">True</span></code> 或 <code class="docutils literal notranslate"><span class="pre">False</span></code>。 默认值是 <code class="docutils literal notranslate"><span class="pre">True</span></code>。 指定是否应该包含指定位置的文件。 此项或 <a class="reference internal" href="#django.forms.FilePathField.allow_folders" title="django.forms.FilePathField.allow_folders"><code class="xref py py-attr docutils literal notranslate"><span class="pre">allow_folders</span></code></a> 必须为 <code class="docutils literal notranslate"><span class="pre">True</span></code>。</p>
</dd></dl>

<dl class="attribute">
<dt id="django.forms.FilePathField.allow_folders">
<code class="descname">allow_folders</code><a class="headerlink" href="#django.forms.FilePathField.allow_folders" title="永久链接至目标">¶</a></dt>
<dd><p>可选。 可选 <code class="docutils literal notranslate"><span class="pre">True</span></code> 或 <code class="docutils literal notranslate"><span class="pre">False</span></code>。 默认为 <code class="docutils literal notranslate"><span class="pre">False</span></code>。 指定是否应包括指定位置的文件夹。 此项或 <a class="reference internal" href="#django.forms.FilePathField.allow_files" title="django.forms.FilePathField.allow_files"><code class="xref py py-attr docutils literal notranslate"><span class="pre">allow_files</span></code></a> 必须为 <code class="docutils literal notranslate"><span class="pre">True</span></code>。</p>
</dd></dl>

</dd></dl>

</div>
<div class="section" id="s-floatfield">
<span id="floatfield"></span><h3><code class="docutils literal notranslate"><span class="pre">FloatField</span></code><a class="headerlink" href="#floatfield" title="永久链接至标题">¶</a></h3>
<dl class="class">
<dt id="django.forms.FloatField">
<em class="property">class </em><code class="descname">FloatField</code>(<em>**kwargs</em>)<a class="headerlink" href="#django.forms.FloatField" title="永久链接至目标">¶</a></dt>
<dd><ul class="simple">
<li>当 <a class="reference internal" href="#django.forms.Field.localize" title="django.forms.Field.localize"><code class="xref py py-attr docutils literal notranslate"><span class="pre">Field.localize</span></code></a> 为 <code class="docutils literal notranslate"><span class="pre">False</span></code> 时是 <a class="reference internal" href="widgets.html#django.forms.NumberInput" title="django.forms.NumberInput"><code class="xref py py-class docutils literal notranslate"><span class="pre">NumberInput</span></code></a> 否则，该字段的默认表单部件是 <a class="reference internal" href="widgets.html#django.forms.TextInput" title="django.forms.TextInput"><code class="xref py py-class docutils literal notranslate"><span class="pre">TextInput</span></code></a>。</li>
<li>空值：<code class="docutils literal notranslate"><span class="pre">None</span></code></li>
<li>规范化为：Python 的浮点数。</li>
<li>验证给定的值是否为浮点数。如果提供了 <code class="docutils literal notranslate"><span class="pre">max_value</span></code> 和 <code class="docutils literal notranslate"><span class="pre">min_value</span></code>，则使用 <a class="reference internal" href="../validators.html#django.core.validators.MaxValueValidator" title="django.core.validators.MaxValueValidator"><code class="xref py py-class docutils literal notranslate"><span class="pre">MaxValueValidator</span></code></a> 和 <a class="reference internal" href="../validators.html#django.core.validators.MinValueValidator" title="django.core.validators.MinValueValidator"><code class="xref py py-class docutils literal notranslate"><span class="pre">MinValueValidator</span></code></a>。允许使用前导空格和后导空格，就像 Python 的 <code class="docutils literal notranslate"><span class="pre">float()</span></code> 函数一样。</li>
<li>错误信息键：<code class="docutils literal notranslate"><span class="pre">required</span></code>、<code class="docutils literal notranslate"><span class="pre">invalid</span></code>、<code class="docutils literal notranslate"><span class="pre">max_value</span></code>、<code class="docutils literal notranslate"><span class="pre">min_value</span></code></li>
</ul>
<p>取两个可选参数：<code class="docutils literal notranslate"><span class="pre">max_value</span></code> 和 <code class="docutils literal notranslate"><span class="pre">min_value</span></code>。这两个参数控制该字段允许的值的范围。</p>
</dd></dl>

</div>
<div class="section" id="s-imagefield">
<span id="imagefield"></span><h3><code class="docutils literal notranslate"><span class="pre">ImageField</span></code><a class="headerlink" href="#imagefield" title="永久链接至标题">¶</a></h3>
<dl class="class">
<dt id="django.forms.ImageField">
<em class="property">class </em><code class="descname">ImageField</code>(<em>**kwargs</em>)<a class="headerlink" href="#django.forms.ImageField" title="永久链接至目标">¶</a></dt>
<dd><ul class="simple">
<li>默认部件：<a class="reference internal" href="widgets.html#django.forms.ClearableFileInput" title="django.forms.ClearableFileInput"><code class="xref py py-class docutils literal notranslate"><span class="pre">ClearableFileInput</span></code></a></li>
<li>空值：<code class="docutils literal notranslate"><span class="pre">None</span></code></li>
<li>规范化为：一个 <code class="docutils literal notranslate"><span class="pre">UploadedFile</span></code> 对象，它将文件内容和文件名包装成一个单一对象。</li>
<li>验证文件数据是否已经绑定到表单中。同时使用 <a class="reference internal" href="../validators.html#django.core.validators.FileExtensionValidator" title="django.core.validators.FileExtensionValidator"><code class="xref py py-class docutils literal notranslate"><span class="pre">FileExtensionValidator</span></code></a> 来验证 Pillow 是否支持文件扩展名。</li>
<li>错误信息键：<code class="docutils literal notranslate"><span class="pre">required</span></code>、<code class="docutils literal notranslate"><span class="pre">invalid</span></code>、<code class="docutils literal notranslate"><span class="pre">missing</span></code>、<code class="docutils literal notranslate"><span class="pre">empty</span></code>、<code class="docutils literal notranslate"><span class="pre">invalid_image</span></code></li>
</ul>
<p>使用 <code class="docutils literal notranslate"><span class="pre">ImageField</span></code> 需要安装的 <a class="reference external" href="https://pillow.readthedocs.io/en/latest/">Pillow</a> 支持你使用的图片格式。如果你在上传图片时遇到 <code class="docutils literal notranslate"><span class="pre">corrupt</span> <span class="pre">image</span></code> 错误，通常意味着 Pillow 不理解图片格式。要解决这个问题，请安装相应的库并重新安装 Pillow。</p>
<p>当你在表单中使用 <code class="docutils literal notranslate"><span class="pre">ImageField</span></code> 时，你还必须记住 <a class="reference internal" href="api.html#binding-uploaded-files"><span class="std std-ref">将文件数据绑定到表单</span></a>。</p>
<p>在字段被清理和验证后，<code class="docutils literal notranslate"><span class="pre">UploadedFile</span></code> 对象将有一个额外的 <code class="docutils literal notranslate"><span class="pre">image</span></code> 属性，包含用于检查文件是否为有效图像的 Pillow <a class="reference external" href="https://pillow.readthedocs.io/en/latest/reference/Image.html">Image</a> 实例。Pillow 在验证图像后关闭了底层文件描述符，所以虽然非图像数据属性如 <code class="docutils literal notranslate"><span class="pre">format</span></code>、<code class="docutils literal notranslate"><span class="pre">height</span></code> 和 <code class="docutils literal notranslate"><span class="pre">width</span></code> 可用，但访问底层图像数据的方法，如 <code class="docutils literal notranslate"><span class="pre">getdata()</span></code> 或 <code class="docutils literal notranslate"><span class="pre">getpixel()</span></code> 如果不重新打开文件，就不能使用。例如：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">PIL</span> <span class="kn">import</span> <span class="n">Image</span>
<span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">django</span> <span class="kn">import</span> <span class="n">forms</span>
<span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">django.core.files.uploadedfile</span> <span class="kn">import</span> <span class="n">SimpleUploadedFile</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">ImageForm</span><span class="p">(</span><span class="n">forms</span><span class="o">.</span><span class="n">Form</span><span class="p">):</span>
<span class="gp">... </span>    <span class="n">img</span> <span class="o">=</span> <span class="n">forms</span><span class="o">.</span><span class="n">ImageField</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">file_data</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;img&#39;</span><span class="p">:</span> <span class="n">SimpleUploadedFile</span><span class="p">(</span><span class="s1">&#39;test.png&#39;</span><span class="p">,</span> <span class="o">&lt;</span><span class="n">file</span> <span class="n">data</span><span class="o">&gt;</span><span class="p">)}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">form</span> <span class="o">=</span> <span class="n">ImageForm</span><span class="p">({},</span> <span class="n">file_data</span><span class="p">)</span>
<span class="go"># Pillow closes the underlying file descriptor.</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">form</span><span class="o">.</span><span class="n">is_valid</span><span class="p">()</span>
<span class="go">True</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">image_field</span> <span class="o">=</span> <span class="n">form</span><span class="o">.</span><span class="n">cleaned_data</span><span class="p">[</span><span class="s1">&#39;img&#39;</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">image_field</span><span class="o">.</span><span class="n">image</span>
<span class="go">&lt;PIL.PngImagePlugin.PngImageFile image mode=RGBA size=191x287 at 0x7F5985045C18&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">image_field</span><span class="o">.</span><span class="n">image</span><span class="o">.</span><span class="n">width</span>
<span class="go">191</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">image_field</span><span class="o">.</span><span class="n">image</span><span class="o">.</span><span class="n">height</span>
<span class="go">287</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">image_field</span><span class="o">.</span><span class="n">image</span><span class="o">.</span><span class="n">format</span>
<span class="go">&#39;PNG&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">image_field</span><span class="o">.</span><span class="n">image</span><span class="o">.</span><span class="n">getdata</span><span class="p">()</span>
<span class="go"># Raises AttributeError: &#39;NoneType&#39; object has no attribute &#39;seek&#39;.</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">image</span> <span class="o">=</span> <span class="n">Image</span><span class="o">.</span><span class="n">open</span><span class="p">(</span><span class="n">image_field</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">image</span><span class="o">.</span><span class="n">getdata</span><span class="p">()</span>
<span class="go">&lt;ImagingCore object at 0x7f5984f874b0&gt;</span>
</pre></div>
</div>
<p>此外，<code class="docutils literal notranslate"><span class="pre">UploadedFile.content_type</span></code> 如果 Pillow 能够确定图片的内容类型，则会以图片的内容类型进行更新，否则会设置为 <code class="docutils literal notranslate"><span class="pre">None</span></code>。</p>
</dd></dl>

</div>
<div class="section" id="s-integerfield">
<span id="integerfield"></span><h3><code class="docutils literal notranslate"><span class="pre">IntegerField</span></code><a class="headerlink" href="#integerfield" title="永久链接至标题">¶</a></h3>
<dl class="class">
<dt id="django.forms.IntegerField">
<em class="property">class </em><code class="descname">IntegerField</code>(<em>**kwargs</em>)<a class="headerlink" href="#django.forms.IntegerField" title="永久链接至目标">¶</a></dt>
<dd><ul class="simple">
<li>当 <a class="reference internal" href="#django.forms.Field.localize" title="django.forms.Field.localize"><code class="xref py py-attr docutils literal notranslate"><span class="pre">Field.localize</span></code></a> 为 <code class="docutils literal notranslate"><span class="pre">False</span></code> 时是 <a class="reference internal" href="widgets.html#django.forms.NumberInput" title="django.forms.NumberInput"><code class="xref py py-class docutils literal notranslate"><span class="pre">NumberInput</span></code></a> 否则，该字段的默认表单部件是 <a class="reference internal" href="widgets.html#django.forms.TextInput" title="django.forms.TextInput"><code class="xref py py-class docutils literal notranslate"><span class="pre">TextInput</span></code></a>。</li>
<li>空值：<code class="docutils literal notranslate"><span class="pre">None</span></code></li>
<li>规范化为：Python 的整数。</li>
<li>验证给定值是否为整数。如果提供了 <code class="docutils literal notranslate"><span class="pre">max_value</span></code> 和 <code class="docutils literal notranslate"><span class="pre">min_value</span></code>，则使用 <a class="reference internal" href="../validators.html#django.core.validators.MaxValueValidator" title="django.core.validators.MaxValueValidator"><code class="xref py py-class docutils literal notranslate"><span class="pre">MaxValueValidator</span></code></a> 和 <a class="reference internal" href="../validators.html#django.core.validators.MinValueValidator" title="django.core.validators.MinValueValidator"><code class="xref py py-class docutils literal notranslate"><span class="pre">MinValueValidator</span></code></a>。允许使用前导空格和后导空格，就像 Python 的 <code class="docutils literal notranslate"><span class="pre">int()</span></code> 函数一样。</li>
<li>错误信息键：<code class="docutils literal notranslate"><span class="pre">required</span></code>、<code class="docutils literal notranslate"><span class="pre">invalid</span></code>、<code class="docutils literal notranslate"><span class="pre">max_value</span></code>、<code class="docutils literal notranslate"><span class="pre">min_value</span></code></li>
</ul>
<p><code class="docutils literal notranslate"><span class="pre">max_value</span></code> 和 <code class="docutils literal notranslate"><span class="pre">min_value</span></code> 的错误信息可能包含 <code class="docutils literal notranslate"><span class="pre">%(limit_value)s</span></code>，将用适当的限制来代替。</p>
<p>需要两个可选参数进行验证：</p>
<dl class="attribute">
<dt id="django.forms.IntegerField.max_value">
<code class="descname">max_value</code><a class="headerlink" href="#django.forms.IntegerField.max_value" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<dl class="attribute">
<dt id="django.forms.IntegerField.min_value">
<code class="descname">min_value</code><a class="headerlink" href="#django.forms.IntegerField.min_value" title="永久链接至目标">¶</a></dt>
<dd><p>这些控制了该字段允许的数值范围。</p>
</dd></dl>

</dd></dl>

</div>
<div class="section" id="s-jsonfield">
<span id="jsonfield"></span><h3><code class="docutils literal notranslate"><span class="pre">JSONField</span></code><a class="headerlink" href="#jsonfield" title="永久链接至标题">¶</a></h3>
<dl class="class">
<dt id="django.forms.JSONField">
<em class="property">class </em><code class="descname">JSONField</code>(<em>encoder=None</em>, <em>decoder=None</em>, <em>**kwargs</em>)<a class="headerlink" href="#django.forms.JSONField" title="永久链接至目标">¶</a></dt>
<dd><div class="versionadded">
<span class="title">New in Django 3.1.</span> </div>
<p>一个接受 JSON 编码数据的字段 <a class="reference internal" href="../models/fields.html#django.db.models.JSONField" title="django.db.models.JSONField"><code class="xref py py-class docutils literal notranslate"><span class="pre">JSONField</span></code></a>。</p>
<ul class="simple">
<li>默认部件：<a class="reference internal" href="widgets.html#django.forms.Textarea" title="django.forms.Textarea"><code class="xref py py-class docutils literal notranslate"><span class="pre">Textarea</span></code></a></li>
<li>空值：<code class="docutils literal notranslate"><span class="pre">None</span></code></li>
<li>规范化为：JSON 值的 Python 表示（通常为 <code class="docutils literal notranslate"><span class="pre">dict</span></code>、<code class="docutils literal notranslate"><span class="pre">list</span></code> 或 <code class="docutils literal notranslate"><span class="pre">None</span></code>），取决于 <a class="reference internal" href="#django.forms.JSONField.decoder" title="django.forms.JSONField.decoder"><code class="xref py py-attr docutils literal notranslate"><span class="pre">JSONField.decoder</span></code></a>。</li>
<li>验证给定值是否为有效的 JSON。</li>
<li>错误信息键：<code class="docutils literal notranslate"><span class="pre">required</span></code>、<code class="docutils literal notranslate"><span class="pre">invalid</span></code></li>
</ul>
<p>需要两个可选的参数：</p>
<dl class="attribute">
<dt id="django.forms.JSONField.encoder">
<code class="descname">encoder</code><a class="headerlink" href="#django.forms.JSONField.encoder" title="永久链接至目标">¶</a></dt>
<dd><p>一个 <a class="reference external" href="https://docs.python.org/3/library/json.html#json.JSONEncoder" title="(在 Python v3.10)"><code class="xref py py-class docutils literal notranslate"><span class="pre">json.JSONEncoder</span></code></a> 子类，用于序列化标准 JSON 序列器不支持的数据类型（例如 <code class="docutils literal notranslate"><span class="pre">datetime.datetime</span></code> 或 <a class="reference external" href="https://docs.python.org/3/library/uuid.html#uuid.UUID" title="(在 Python v3.10)"><code class="xref py py-class docutils literal notranslate"><span class="pre">UUID</span></code></a>）。例如，你可以使用 <a class="reference internal" href="../../topics/serialization.html#django.core.serializers.json.DjangoJSONEncoder" title="django.core.serializers.json.DjangoJSONEncoder"><code class="xref py py-class docutils literal notranslate"><span class="pre">DjangoJSONEncoder</span></code></a> 类。</p>
<p>默认为 <code class="docutils literal notranslate"><span class="pre">json.JSONEncoder</span></code>。</p>
</dd></dl>

<dl class="attribute">
<dt id="django.forms.JSONField.decoder">
<code class="descname">decoder</code><a class="headerlink" href="#django.forms.JSONField.decoder" title="永久链接至目标">¶</a></dt>
<dd><p>一个 <a class="reference external" href="https://docs.python.org/3/library/json.html#json.JSONDecoder" title="(在 Python v3.10)"><code class="xref py py-class docutils literal notranslate"><span class="pre">json.JSONDecoder</span></code></a> 子类来反序列化输入。你的反序列化可能需要考虑到你无法确定输入类型的事实。例如，你有可能返回一个 <code class="docutils literal notranslate"><span class="pre">datetime</span></code>，但实际上是一个字符串，而这个字符串恰好与 <code class="docutils literal notranslate"><span class="pre">datetime</span></code> 的格式相同。</p>
<p><code class="docutils literal notranslate"><span class="pre">decoder</span></code> 可用于验证输入。如果在反序列化过程中出现 <code class="xref py py-class docutils literal notranslate"><span class="pre">json.JSONONDecodeError</span></code>，则会出现 <code class="docutils literal notranslate"><span class="pre">ValidationError</span></code>。</p>
<p>默认为 <code class="docutils literal notranslate"><span class="pre">json.JSONDecoder</span></code>。</p>
</dd></dl>

<div class="admonition note">
<p class="first admonition-title">注解</p>
<p class="last">如果你使用 <a class="reference internal" href="../../topics/forms/modelforms.html#django.forms.ModelForm" title="django.forms.ModelForm"><code class="xref py py-class docutils literal notranslate"><span class="pre">ModelForm</span></code></a>，将使用 <a class="reference internal" href="../models/fields.html#django.db.models.JSONField" title="django.db.models.JSONField"><code class="xref py py-class docutils literal notranslate"><span class="pre">JSONField</span></code></a> 中的 <code class="docutils literal notranslate"><span class="pre">encoder</span></code> 和 <code class="docutils literal notranslate"><span class="pre">decoder</span></code>。</p>
</div>
<div class="admonition-user-friendly-forms admonition">
<p class="first admonition-title">用户友好的表单</p>
<p class="last"><code class="docutils literal notranslate"><span class="pre">JSONField</span></code> 在大多数情况下不是特别方便用户使用。但是，它是一种有用的方式，可以将客户端部件的数据格式化，以便提交给服务器。</p>
</div>
</dd></dl>

</div>
<div class="section" id="s-genericipaddressfield">
<span id="genericipaddressfield"></span><h3><code class="docutils literal notranslate"><span class="pre">GenericIPAddressField</span></code><a class="headerlink" href="#genericipaddressfield" title="永久链接至标题">¶</a></h3>
<dl class="class">
<dt id="django.forms.GenericIPAddressField">
<em class="property">class </em><code class="descname">GenericIPAddressField</code>(<em>**kwargs</em>)<a class="headerlink" href="#django.forms.GenericIPAddressField" title="永久链接至目标">¶</a></dt>
<dd><p>一个包含 IPv4 或 IPv6地址 的字段。</p>
<ul class="simple">
<li>默认部件：<a class="reference internal" href="widgets.html#django.forms.TextInput" title="django.forms.TextInput"><code class="xref py py-class docutils literal notranslate"><span class="pre">TextInput</span></code></a></li>
<li>空值：<code class="docutils literal notranslate"><span class="pre">''</span></code> （空字符串）</li>
<li>规范化为：一个字符串。IPv6 地址的规范化如下所述。</li>
<li>验证给定的值是一个有效的 IP 地址。</li>
<li>错误信息键：<code class="docutils literal notranslate"><span class="pre">required</span></code>、<code class="docutils literal notranslate"><span class="pre">invalid</span></code></li>
</ul>
<p>IPv6 地址规范化遵循 <span class="target" id="index-2"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc4291.html#section-2.2"><strong>RFC 4291#section-2.2</strong></a> 第 2.2 节，包括使用该节第 3 段建议的 IPv4 格式，如 <code class="docutils literal notranslate"><span class="pre">::fffff:192.0.2.0</span></code>。例如，<code class="docutils literal notranslate"><span class="pre">2001:0::0:01</span></code> 将被标准化为 <code class="docutils literal notranslate"><span class="pre">2001::1</span></code>，<code class="docutils literal notranslate"><span class="pre">::fffff:0a0a:0a0a</span></code> 将被标准化为 <code class="docutils literal notranslate"><span class="pre">::fffff:10.10.10.10</span></code>。所有字符都转换为小写。</p>
<p>需要两个可选的参数：</p>
<dl class="attribute">
<dt id="django.forms.GenericIPAddressField.protocol">
<code class="descname">protocol</code><a class="headerlink" href="#django.forms.GenericIPAddressField.protocol" title="永久链接至目标">¶</a></dt>
<dd><p>将有效输入限制为指定协议。接受的值是 <code class="docutils literal notranslate"><span class="pre">both</span></code> （默认）、<code class="docutils literal notranslate"><span class="pre">IPv4</span></code> 或 <code class="docutils literal notranslate"><span class="pre">IPv6</span></code>。匹配是不区分大小写的。</p>
</dd></dl>

<dl class="attribute">
<dt id="django.forms.GenericIPAddressField.unpack_ipv4">
<code class="descname">unpack_ipv4</code><a class="headerlink" href="#django.forms.GenericIPAddressField.unpack_ipv4" title="永久链接至目标">¶</a></dt>
<dd><p>解压 IPv4 映射地址，如 <code class="docutils literal notranslate"><span class="pre">::fffff:192.0.2.1</span></code>。如果启用该选项，该地址将被解压为 <code class="docutils literal notranslate"><span class="pre">192.0.2.1</span></code>。默认为禁用。只有当 <code class="docutils literal notranslate"><span class="pre">protocol</span></code> 设置为 <code class="docutils literal notranslate"><span class="pre">'both'</span></code> 时才会启用。</p>
</dd></dl>

</dd></dl>

</div>
<div class="section" id="s-multiplechoicefield">
<span id="multiplechoicefield"></span><h3><code class="docutils literal notranslate"><span class="pre">MultipleChoiceField</span></code><a class="headerlink" href="#multiplechoicefield" title="永久链接至标题">¶</a></h3>
<dl class="class">
<dt id="django.forms.MultipleChoiceField">
<em class="property">class </em><code class="descname">MultipleChoiceField</code>(<em>**kwargs</em>)<a class="headerlink" href="#django.forms.MultipleChoiceField" title="永久链接至目标">¶</a></dt>
<dd><ul class="simple">
<li>默认部件：<a class="reference internal" href="widgets.html#django.forms.SelectMultiple" title="django.forms.SelectMultiple"><code class="xref py py-class docutils literal notranslate"><span class="pre">SelectMultiple</span></code></a></li>
<li>空值：<code class="docutils literal notranslate"><span class="pre">[]</span></code> （空列表）</li>
<li>规范化为：一个字符串列表。</li>
<li>验证给定值列表中的每个值是否存在于选择列表中。</li>
<li>错误信息键：<code class="docutils literal notranslate"><span class="pre">required</span></code>、<code class="docutils literal notranslate"><span class="pre">invalid_choice</span></code>、<code class="docutils literal notranslate"><span class="pre">invalid_list</span></code></li>
</ul>
<p><code class="docutils literal notranslate"><span class="pre">invalid_choice</span></code> 错误信息可能包含 <code class="docutils literal notranslate"><span class="pre">%(value)s</span></code>，该信息将被替换为选定的选择。</p>
<p>与 <a class="reference internal" href="#django.forms.ChoiceField" title="django.forms.ChoiceField"><code class="xref py py-class docutils literal notranslate"><span class="pre">ChoiceField</span></code></a> 一样，多了一个必要参数 <code class="docutils literal notranslate"><span class="pre">choices</span></code>。</p>
</dd></dl>

</div>
<div class="section" id="s-typedmultiplechoicefield">
<span id="typedmultiplechoicefield"></span><h3><code class="docutils literal notranslate"><span class="pre">TypedMultipleChoiceField</span></code><a class="headerlink" href="#typedmultiplechoicefield" title="永久链接至标题">¶</a></h3>
<dl class="class">
<dt id="django.forms.TypedMultipleChoiceField">
<em class="property">class </em><code class="descname">TypedMultipleChoiceField</code>(<em>**kwargs</em>)<a class="headerlink" href="#django.forms.TypedMultipleChoiceField" title="永久链接至目标">¶</a></dt>
<dd><p>就像 <a class="reference internal" href="#django.forms.MultipleChoiceField" title="django.forms.MultipleChoiceField"><code class="xref py py-class docutils literal notranslate"><span class="pre">MultipleChoiceField</span></code></a> 一样，只是 <a class="reference internal" href="#django.forms.TypedMultipleChoiceField" title="django.forms.TypedMultipleChoiceField"><code class="xref py py-class docutils literal notranslate"><span class="pre">TypedMultipleChoiceField</span></code></a> 需要两个额外的参数：<code class="docutils literal notranslate"><span class="pre">coerce</span></code> 和 <code class="docutils literal notranslate"><span class="pre">empty_value</span></code>。</p>
<ul class="simple">
<li>默认部件：<a class="reference internal" href="widgets.html#django.forms.SelectMultiple" title="django.forms.SelectMultiple"><code class="xref py py-class docutils literal notranslate"><span class="pre">SelectMultiple</span></code></a></li>
<li>空值：不管你给 <code class="xref py py-attr docutils literal notranslate"><span class="pre">empty_value</span></code> 的是什么。</li>
<li>归法化为：<code class="docutils literal notranslate"><span class="pre">coerce</span></code> 参数提供的类型值列表。</li>
<li>验证给定的值是否存在于选择列表中，并且可以被强制执行。</li>
<li>错误信息键：<code class="docutils literal notranslate"><span class="pre">required</span></code>、<code class="docutils literal notranslate"><span class="pre">invalid_choice</span></code></li>
</ul>
<p><code class="docutils literal notranslate"><span class="pre">invalid_choice</span></code> 错误信息可能包含 <code class="docutils literal notranslate"><span class="pre">%(value)s</span></code>，该信息将被替换为选定的选择。</p>
<p>需要两个额外的参数，<code class="docutils literal notranslate"><span class="pre">coerce</span></code> 和 <code class="docutils literal notranslate"><span class="pre">empty_value</span></code>，如 <a class="reference internal" href="#django.forms.TypedChoiceField" title="django.forms.TypedChoiceField"><code class="xref py py-class docutils literal notranslate"><span class="pre">TypedChoiceField</span></code></a>。</p>
</dd></dl>

</div>
<div class="section" id="s-nullbooleanfield">
<span id="nullbooleanfield"></span><h3><code class="docutils literal notranslate"><span class="pre">NullBooleanField</span></code><a class="headerlink" href="#nullbooleanfield" title="永久链接至标题">¶</a></h3>
<dl class="class">
<dt id="django.forms.NullBooleanField">
<em class="property">class </em><code class="descname">NullBooleanField</code>(<em>**kwargs</em>)<a class="headerlink" href="#django.forms.NullBooleanField" title="永久链接至目标">¶</a></dt>
<dd><ul class="simple">
<li>默认部件：<a class="reference internal" href="widgets.html#django.forms.NullBooleanSelect" title="django.forms.NullBooleanSelect"><code class="xref py py-class docutils literal notranslate"><span class="pre">NullBooleanSelect</span></code></a></li>
<li>空值：<code class="docutils literal notranslate"><span class="pre">None</span></code></li>
<li>规范化为：Python 的 <code class="docutils literal notranslate"><span class="pre">True</span></code>、<code class="docutils literal notranslate"><span class="pre">False</span></code> 或 <code class="docutils literal notranslate"><span class="pre">None</span></code> 值。</li>
<li>不验证任何东西（也就是说，它从不引起 <code class="docutils literal notranslate"><span class="pre">ValidationError</span></code>）。</li>
</ul>
<p><code class="docutils literal notranslate"><span class="pre">NullBooleanField</span></code> 可以通过提供部件 <code class="docutils literal notranslate"><span class="pre">choices</span></code> 来与诸如 <a class="reference internal" href="widgets.html#django.forms.Select" title="django.forms.Select"><code class="xref py py-class docutils literal notranslate"><span class="pre">Select</span></code></a> 或 <a class="reference internal" href="widgets.html#django.forms.RadioSelect" title="django.forms.RadioSelect"><code class="xref py py-class docutils literal notranslate"><span class="pre">RadioSelect</span></code></a> 等部件一起使用。</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">NullBooleanField</span><span class="p">(</span>
    <span class="n">widget</span><span class="o">=</span><span class="n">Select</span><span class="p">(</span>
        <span class="n">choices</span><span class="o">=</span><span class="p">[</span>
            <span class="p">(</span><span class="s1">&#39;&#39;</span><span class="p">,</span> <span class="s1">&#39;Unknown&#39;</span><span class="p">),</span>
            <span class="p">(</span><span class="kc">True</span><span class="p">,</span> <span class="s1">&#39;Yes&#39;</span><span class="p">),</span>
            <span class="p">(</span><span class="kc">False</span><span class="p">,</span> <span class="s1">&#39;No&#39;</span><span class="p">),</span>
        <span class="p">]</span>
    <span class="p">)</span>
<span class="p">)</span>
</pre></div>
</div>
</dd></dl>

</div>
<div class="section" id="s-regexfield">
<span id="regexfield"></span><h3><code class="docutils literal notranslate"><span class="pre">RegexField</span></code><a class="headerlink" href="#regexfield" title="永久链接至标题">¶</a></h3>
<dl class="class">
<dt id="django.forms.RegexField">
<em class="property">class </em><code class="descname">RegexField</code>(<em>**kwargs</em>)<a class="headerlink" href="#django.forms.RegexField" title="永久链接至目标">¶</a></dt>
<dd><ul class="simple">
<li>默认部件：<a class="reference internal" href="widgets.html#django.forms.TextInput" title="django.forms.TextInput"><code class="xref py py-class docutils literal notranslate"><span class="pre">TextInput</span></code></a></li>
<li>空值：不管你给 <code class="xref py py-attr docutils literal notranslate"><span class="pre">empty_value</span></code> 的是什么。</li>
<li>规范化为：一个字符串。</li>
<li>使用 <a class="reference internal" href="../validators.html#django.core.validators.RegexValidator" title="django.core.validators.RegexValidator"><code class="xref py py-class docutils literal notranslate"><span class="pre">RegexValidator</span></code></a> 来验证给定的值是否匹配某个正则表达式。</li>
<li>错误信息键：<code class="docutils literal notranslate"><span class="pre">required</span></code>、<code class="docutils literal notranslate"><span class="pre">invalid</span></code></li>
</ul>
<p>需要一个额外的参数：</p>
<dl class="attribute">
<dt id="django.forms.RegexField.regex">
<code class="descname">regex</code><a class="headerlink" href="#django.forms.RegexField.regex" title="永久链接至目标">¶</a></dt>
<dd><p>一个正则表达式，可以是字符串，也可以是编译后的正则表达式对象。</p>
</dd></dl>

<p>也接受 <code class="docutils literal notranslate"><span class="pre">max_length</span></code>、<code class="docutils literal notranslate"><span class="pre">min_length</span></code>、<code class="docutils literal notranslate"><span class="pre">strip</span></code> 和 <code class="docutils literal notranslate"><span class="pre">empty_value</span></code>，它们的工作原理和 <a class="reference internal" href="#django.forms.CharField" title="django.forms.CharField"><code class="xref py py-class docutils literal notranslate"><span class="pre">CharField</span></code></a> 一样。</p>
<dl class="attribute">
<dt id="django.forms.RegexField.strip">
<code class="descname">strip</code><a class="headerlink" href="#django.forms.RegexField.strip" title="永久链接至目标">¶</a></dt>
<dd><p>默认值为 <code class="docutils literal notranslate"><span class="pre">False</span></code>。如果启用，将在验证正则表达式之前进行 strip。</p>
</dd></dl>

</dd></dl>

</div>
<div class="section" id="s-slugfield">
<span id="slugfield"></span><h3><code class="docutils literal notranslate"><span class="pre">SlugField</span></code><a class="headerlink" href="#slugfield" title="永久链接至标题">¶</a></h3>
<dl class="class">
<dt id="django.forms.SlugField">
<em class="property">class </em><code class="descname">SlugField</code>(<em>**kwargs</em>)<a class="headerlink" href="#django.forms.SlugField" title="永久链接至目标">¶</a></dt>
<dd><ul class="simple">
<li>默认部件：<a class="reference internal" href="widgets.html#django.forms.TextInput" title="django.forms.TextInput"><code class="xref py py-class docutils literal notranslate"><span class="pre">TextInput</span></code></a></li>
<li>空值：不管你给 <a class="reference internal" href="#django.forms.SlugField.empty_value" title="django.forms.SlugField.empty_value"><code class="xref py py-attr docutils literal notranslate"><span class="pre">empty_value</span></code></a> 的是什么。</li>
<li>规范化为：一个字符串。</li>
<li>使用 <a class="reference internal" href="../validators.html#django.core.validators.validate_slug" title="django.core.validators.validate_slug"><code class="xref py py-class docutils literal notranslate"><span class="pre">validate_slug</span></code></a> 或 <a class="reference internal" href="../validators.html#django.core.validators.validate_unicode_slug" title="django.core.validators.validate_unicode_slug"><code class="xref py py-class docutils literal notranslate"><span class="pre">validate_unicode_slug</span></code></a> 来验证给定值是否只包含字母、数字、下划线和连字符。</li>
<li>错误信息键：<code class="docutils literal notranslate"><span class="pre">required</span></code>、<code class="docutils literal notranslate"><span class="pre">invalid</span></code></li>
</ul>
<p>这个字段用于在表单中表示一个模型 <a class="reference internal" href="../models/fields.html#django.db.models.SlugField" title="django.db.models.SlugField"><code class="xref py py-class docutils literal notranslate"><span class="pre">SlugField</span></code></a>。</p>
<p>需要两个可选的参数：</p>
<dl class="attribute">
<dt id="django.forms.SlugField.allow_unicode">
<code class="descname">allow_unicode</code><a class="headerlink" href="#django.forms.SlugField.allow_unicode" title="永久链接至目标">¶</a></dt>
<dd><p>一个布尔值，指示该字段除了接受 ASCII 字母外，还接受 Unicode 字母。默认值为 <code class="docutils literal notranslate"><span class="pre">False</span></code>。</p>
</dd></dl>

<dl class="attribute">
<dt id="django.forms.SlugField.empty_value">
<code class="descname">empty_value</code><a class="headerlink" href="#django.forms.SlugField.empty_value" title="永久链接至目标">¶</a></dt>
<dd><p>用来表示“空”的值。默认为空字符串。</p>
</dd></dl>

</dd></dl>

</div>
<div class="section" id="s-timefield">
<span id="timefield"></span><h3><code class="docutils literal notranslate"><span class="pre">TimeField</span></code><a class="headerlink" href="#timefield" title="永久链接至标题">¶</a></h3>
<dl class="class">
<dt id="django.forms.TimeField">
<em class="property">class </em><code class="descname">TimeField</code>(<em>**kwargs</em>)<a class="headerlink" href="#django.forms.TimeField" title="永久链接至目标">¶</a></dt>
<dd><ul class="simple">
<li>默认部件：<a class="reference internal" href="widgets.html#django.forms.TimeInput" title="django.forms.TimeInput"><code class="xref py py-class docutils literal notranslate"><span class="pre">TimeInput</span></code></a></li>
<li>空值：<code class="docutils literal notranslate"><span class="pre">None</span></code></li>
<li>规范化为：Python 的 <code class="docutils literal notranslate"><span class="pre">datetime.time</span></code> 对象。</li>
<li>验证给定值是 <code class="docutils literal notranslate"><span class="pre">datetime.time</span></code> 或以特定时间格式化的字符串。</li>
<li>错误信息键：<code class="docutils literal notranslate"><span class="pre">required</span></code>、<code class="docutils literal notranslate"><span class="pre">invalid</span></code></li>
</ul>
<p>需要一个可选的参数：</p>
<dl class="attribute">
<dt id="django.forms.TimeField.input_formats">
<code class="descname">input_formats</code><a class="headerlink" href="#django.forms.TimeField.input_formats" title="永久链接至目标">¶</a></dt>
<dd><p>用于将字符串转换为有效的 <code class="docutils literal notranslate"><span class="pre">datetime.time</span></code> 对象的格式列表。</p>
</dd></dl>

<p>如果没有提供 <code class="docutils literal notranslate"><span class="pre">input_formats</span></code> 参数，如果 <a class="reference internal" href="../settings.html#std:setting-USE_L10N"><code class="xref std std-setting docutils literal notranslate"><span class="pre">USE_L10N</span></code></a> 为 <code class="docutils literal notranslate"><span class="pre">False</span></code>，则默认输入格式来自 <code class="xref std std-setting docutils literal notranslate"><span class="pre">TIME_INPUT_FORMATS`</span></code>，如果启用了本地化，则来自激活的本地格式 <code class="docutils literal notranslate"><span class="pre">TIME_INPUT_FORMATS</span></code> 键。也请参见 <a class="reference internal" href="../../topics/i18n/formatting.html"><span class="doc">格式本地化</span></a>。</p>
</dd></dl>

</div>
<div class="section" id="s-urlfield">
<span id="urlfield"></span><h3><code class="docutils literal notranslate"><span class="pre">URLField</span></code><a class="headerlink" href="#urlfield" title="永久链接至标题">¶</a></h3>
<dl class="class">
<dt id="django.forms.URLField">
<em class="property">class </em><code class="descname">URLField</code>(<em>**kwargs</em>)<a class="headerlink" href="#django.forms.URLField" title="永久链接至目标">¶</a></dt>
<dd><ul class="simple">
<li>默认部件：<a class="reference internal" href="widgets.html#django.forms.URLInput" title="django.forms.URLInput"><code class="xref py py-class docutils literal notranslate"><span class="pre">URLInput</span></code></a></li>
<li>空值：不管你给 <code class="xref py py-attr docutils literal notranslate"><span class="pre">empty_value</span></code> 的是什么。</li>
<li>规范化为：一个字符串。</li>
<li>使用 <a class="reference internal" href="../validators.html#django.core.validators.URLValidator" title="django.core.validators.URLValidator"><code class="xref py py-class docutils literal notranslate"><span class="pre">URLValidator</span></code></a> 来验证给定值是一个有效的 URL。</li>
<li>错误信息键：<code class="docutils literal notranslate"><span class="pre">required</span></code>、<code class="docutils literal notranslate"><span class="pre">invalid</span></code></li>
</ul>
<p>有三个可选参数 <code class="docutils literal notranslate"><span class="pre">max_length</span></code>、<code class="docutils literal notranslate"><span class="pre">min_length</span></code> 和 <code class="docutils literal notranslate"><span class="pre">empty_value</span></code>，它们的工作原理与 <a class="reference internal" href="#django.forms.CharField" title="django.forms.CharField"><code class="xref py py-class docutils literal notranslate"><span class="pre">CharField</span></code></a> 一样。</p>
</dd></dl>

</div>
<div class="section" id="s-uuidfield">
<span id="uuidfield"></span><h3><code class="docutils literal notranslate"><span class="pre">UUIDField</span></code><a class="headerlink" href="#uuidfield" title="永久链接至标题">¶</a></h3>
<dl class="class">
<dt id="django.forms.UUIDField">
<em class="property">class </em><code class="descname">UUIDField</code>(<em>**kwargs</em>)<a class="headerlink" href="#django.forms.UUIDField" title="永久链接至目标">¶</a></dt>
<dd><ul class="simple">
<li>默认部件：<a class="reference internal" href="widgets.html#django.forms.TextInput" title="django.forms.TextInput"><code class="xref py py-class docutils literal notranslate"><span class="pre">TextInput</span></code></a></li>
<li>空值：<code class="docutils literal notranslate"><span class="pre">None</span></code></li>
<li>规范化为：<a class="reference external" href="https://docs.python.org/3/library/uuid.html#uuid.UUID" title="(在 Python v3.10)"><code class="xref py py-class docutils literal notranslate"><span class="pre">UUID</span></code></a> 对象。</li>
<li>错误信息键：<code class="docutils literal notranslate"><span class="pre">required</span></code>、<code class="docutils literal notranslate"><span class="pre">invalid</span></code></li>
</ul>
<p>该字段将接受作为 <a class="reference external" href="https://docs.python.org/3/library/uuid.html#uuid.UUID" title="(在 Python v3.10)"><code class="xref py py-class docutils literal notranslate"><span class="pre">UUID</span></code></a> 构造函数的 <code class="docutils literal notranslate"><span class="pre">hex</span></code> 参数的任何字符串格式。</p>
</dd></dl>

</div>
</div>
<div class="section" id="s-slightly-complex-built-in-field-classes">
<span id="slightly-complex-built-in-field-classes"></span><h2>稍复杂的内置 <code class="docutils literal notranslate"><span class="pre">Field</span></code> 类<a class="headerlink" href="#slightly-complex-built-in-field-classes" title="永久链接至标题">¶</a></h2>
<div class="section" id="s-combofield">
<span id="combofield"></span><h3><code class="docutils literal notranslate"><span class="pre">ComboField</span></code><a class="headerlink" href="#combofield" title="永久链接至标题">¶</a></h3>
<dl class="class">
<dt id="django.forms.ComboField">
<em class="property">class </em><code class="descname">ComboField</code>(<em>**kwargs</em>)<a class="headerlink" href="#django.forms.ComboField" title="永久链接至目标">¶</a></dt>
<dd><ul class="simple">
<li>默认部件：<a class="reference internal" href="widgets.html#django.forms.TextInput" title="django.forms.TextInput"><code class="xref py py-class docutils literal notranslate"><span class="pre">TextInput</span></code></a></li>
<li>空值：<code class="docutils literal notranslate"><span class="pre">''</span></code> （空字符串）</li>
<li>规范化为：一个字符串。</li>
<li>根据 <code class="docutils literal notranslate"><span class="pre">ComboField</span></code> 参数指定的每个字段验证给定值。</li>
<li>错误信息键：<code class="docutils literal notranslate"><span class="pre">required</span></code>、<code class="docutils literal notranslate"><span class="pre">invalid</span></code></li>
</ul>
<p>需要一个额外的必要参数。</p>
<dl class="attribute">
<dt id="django.forms.ComboField.fields">
<code class="descname">fields</code><a class="headerlink" href="#django.forms.ComboField.fields" title="永久链接至目标">¶</a></dt>
<dd><p>应该用来验证字段值的字段列表（按照提供的顺序）。</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">django.forms</span> <span class="kn">import</span> <span class="n">ComboField</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span> <span class="o">=</span> <span class="n">ComboField</span><span class="p">(</span><span class="n">fields</span><span class="o">=</span><span class="p">[</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">20</span><span class="p">),</span> <span class="n">EmailField</span><span class="p">()])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="o">.</span><span class="n">clean</span><span class="p">(</span><span class="s1">&#39;test@example.com&#39;</span><span class="p">)</span>
<span class="go">&#39;test@example.com&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="o">.</span><span class="n">clean</span><span class="p">(</span><span class="s1">&#39;longemailaddress@example.com&#39;</span><span class="p">)</span>
<span class="gt">Traceback (most recent call last):</span>
<span class="c">...</span>
<span class="gr">ValidationError</span>: <span class="n">[&#39;Ensure this value has at most 20 characters (it has 28).&#39;]</span>
</pre></div>
</div>
</dd></dl>

</dd></dl>

</div>
<div class="section" id="s-multivaluefield">
<span id="multivaluefield"></span><h3><code class="docutils literal notranslate"><span class="pre">MultiValueField</span></code><a class="headerlink" href="#multivaluefield" title="永久链接至标题">¶</a></h3>
<dl class="class">
<dt id="django.forms.MultiValueField">
<em class="property">class </em><code class="descname">MultiValueField</code>(<em>fields=()</em>, <em>**kwargs</em>)<a class="headerlink" href="#django.forms.MultiValueField" title="永久链接至目标">¶</a></dt>
<dd><ul class="simple">
<li>默认部件：<a class="reference internal" href="widgets.html#django.forms.TextInput" title="django.forms.TextInput"><code class="xref py py-class docutils literal notranslate"><span class="pre">TextInput</span></code></a></li>
<li>空值：<code class="docutils literal notranslate"><span class="pre">''</span></code> （空字符串）</li>
<li>规范化为：子类的 <code class="docutils literal notranslate"><span class="pre">compress</span></code> 方法返回的类型。</li>
<li>根据作为 <code class="docutils literal notranslate"><span class="pre">MultiValueField</span></code> 参数指定的每个字段验证给定值。</li>
<li>错误信息键：<code class="docutils literal notranslate"><span class="pre">required</span></code>、<code class="docutils literal notranslate"><span class="pre">invalid</span></code>、<code class="docutils literal notranslate"><span class="pre">incomplete</span></code></li>
</ul>
<p>将多个字段的逻辑聚合在一起产生一个值。</p>
<p>这个字段是抽象的，必须被子类化。与单值字段相反， <a class="reference internal" href="#django.forms.MultiValueField" title="django.forms.MultiValueField"><code class="xref py py-class docutils literal notranslate"><span class="pre">MultiValueField</span></code></a> 的子类不能实现 <a class="reference internal" href="#django.forms.Field.clean" title="django.forms.Field.clean"><code class="xref py py-meth docutils literal notranslate"><span class="pre">clean()</span></code></a>，而是——实现 <a class="reference internal" href="#django.forms.MultiValueField.compress" title="django.forms.MultiValueField.compress"><code class="xref py py-meth docutils literal notranslate"><span class="pre">compress()</span></code></a>。</p>
<p>需要一个额外的必要参数。</p>
<dl class="attribute">
<dt id="django.forms.MultiValueField.fields">
<code class="descname">fields</code><a class="headerlink" href="#django.forms.MultiValueField.fields" title="永久链接至目标">¶</a></dt>
<dd><p>字段组成的元组，其值经清理后合并为一个值。 字段的每个值都由 <code class="docutils literal notranslate"><span class="pre">fields</span></code> 中的相应字段进行清理——第一个值由第一个字段清理，第二个值由第二个字段清理，等等。当所有字段清理完毕后，通过 <a class="reference internal" href="#django.forms.MultiValueField.compress" title="django.forms.MultiValueField.compress"><code class="xref py py-meth docutils literal notranslate"><span class="pre">compress()</span></code></a> 将清理后的值列表合并为一个值。</p>
</dd></dl>

<p>还需要一些可选的参数：</p>
<dl class="attribute">
<dt id="django.forms.MultiValueField.require_all_fields">
<code class="descname">require_all_fields</code><a class="headerlink" href="#django.forms.MultiValueField.require_all_fields" title="永久链接至目标">¶</a></dt>
<dd><p>默认值为 <code class="docutils literal notranslate"><span class="pre">True</span></code>，在这种情况下，如果没有为任何字段提供值，就会出现 <code class="docutils literal notranslate"><span class="pre">required</span></code> 验证错误。</p>
<p><a class="reference internal" href="#django.forms.Field.required" title="django.forms.Field.required"><code class="xref py py-attr docutils literal notranslate"><span class="pre">Field.required</span></code></a> 属性设置为 <code class="docutils literal notranslate"><span class="pre">False</span></code> 时，可将单个字段设置为 <code class="docutils literal notranslate"><span class="pre">False</span></code>，使其成为可选字段。如果没有为必填字段提供任何值，就会出现 <code class="docutils literal notranslate"><span class="pre">incomplete</span></code> 的验证错误。</p>
<p>可以在 <a class="reference internal" href="#django.forms.MultiValueField" title="django.forms.MultiValueField"><code class="xref py py-class docutils literal notranslate"><span class="pre">MultiValueField</span></code></a> 子类上定义一个默认的 <code class="docutils literal notranslate"><span class="pre">incomplete</span></code> 错误信息，也可以在每个单独的字段上定义不同的信息。例如：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.core.validators</span> <span class="kn">import</span> <span class="n">RegexValidator</span>

<span class="k">class</span> <span class="nc">PhoneField</span><span class="p">(</span><span class="n">MultiValueField</span><span class="p">):</span>
    <span class="k">def</span> <span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
        <span class="c1"># Define one message for all fields.</span>
        <span class="n">error_messages</span> <span class="o">=</span> <span class="p">{</span>
            <span class="s1">&#39;incomplete&#39;</span><span class="p">:</span> <span class="s1">&#39;Enter a country calling code and a phone number.&#39;</span><span class="p">,</span>
        <span class="p">}</span>
        <span class="c1"># Or define a different message for each field.</span>
        <span class="n">fields</span> <span class="o">=</span> <span class="p">(</span>
            <span class="n">CharField</span><span class="p">(</span>
                <span class="n">error_messages</span><span class="o">=</span><span class="p">{</span><span class="s1">&#39;incomplete&#39;</span><span class="p">:</span> <span class="s1">&#39;Enter a country calling code.&#39;</span><span class="p">},</span>
                <span class="n">validators</span><span class="o">=</span><span class="p">[</span>
                    <span class="n">RegexValidator</span><span class="p">(</span><span class="sa">r</span><span class="s1">&#39;^[0-9]+$&#39;</span><span class="p">,</span> <span class="s1">&#39;Enter a valid country calling code.&#39;</span><span class="p">),</span>
                <span class="p">],</span>
            <span class="p">),</span>
            <span class="n">CharField</span><span class="p">(</span>
                <span class="n">error_messages</span><span class="o">=</span><span class="p">{</span><span class="s1">&#39;incomplete&#39;</span><span class="p">:</span> <span class="s1">&#39;Enter a phone number.&#39;</span><span class="p">},</span>
                <span class="n">validators</span><span class="o">=</span><span class="p">[</span><span class="n">RegexValidator</span><span class="p">(</span><span class="sa">r</span><span class="s1">&#39;^[0-9]+$&#39;</span><span class="p">,</span> <span class="s1">&#39;Enter a valid phone number.&#39;</span><span class="p">)],</span>
            <span class="p">),</span>
            <span class="n">CharField</span><span class="p">(</span>
                <span class="n">validators</span><span class="o">=</span><span class="p">[</span><span class="n">RegexValidator</span><span class="p">(</span><span class="sa">r</span><span class="s1">&#39;^[0-9]+$&#39;</span><span class="p">,</span> <span class="s1">&#39;Enter a valid extension.&#39;</span><span class="p">)],</span>
                <span class="n">required</span><span class="o">=</span><span class="kc">False</span><span class="p">,</span>
            <span class="p">),</span>
        <span class="p">)</span>
        <span class="nb">super</span><span class="p">()</span><span class="o">.</span><span class="fm">__init__</span><span class="p">(</span>
            <span class="n">error_messages</span><span class="o">=</span><span class="n">error_messages</span><span class="p">,</span> <span class="n">fields</span><span class="o">=</span><span class="n">fields</span><span class="p">,</span>
            <span class="n">require_all_fields</span><span class="o">=</span><span class="kc">False</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span>
        <span class="p">)</span>
</pre></div>
</div>
</dd></dl>

<dl class="attribute">
<dt id="django.forms.MultiValueField.widget">
<code class="descname">widget</code><a class="headerlink" href="#django.forms.MultiValueField.widget" title="永久链接至目标">¶</a></dt>
<dd><p>必须是 <a class="reference internal" href="widgets.html#django.forms.MultiWidget" title="django.forms.MultiWidget"><code class="xref py py-class docutils literal notranslate"><span class="pre">django.forms.MultiWidget</span></code></a> 的子类。默认值是 <a class="reference internal" href="widgets.html#django.forms.TextInput" title="django.forms.TextInput"><code class="xref py py-class docutils literal notranslate"><span class="pre">TextInput</span></code></a>，在这种情况下可能不是很有用。</p>
</dd></dl>

<dl class="method">
<dt id="django.forms.MultiValueField.compress">
<code class="descname">compress</code>(<em>data_list</em>)<a class="headerlink" href="#django.forms.MultiValueField.compress" title="永久链接至目标">¶</a></dt>
<dd><p>取一个有效值的列表，并返回这些值的“压缩”版本——在一个单一值中。例如，<a class="reference internal" href="#django.forms.SplitDateTimeField" title="django.forms.SplitDateTimeField"><code class="xref py py-class docutils literal notranslate"><span class="pre">SplitDateTimeField</span></code></a> 是一个子类，它将一个时间字段和一个日期字段合并成一个 <code class="docutils literal notranslate"><span class="pre">datetime</span></code> 对象。</p>
<p>这个方法必须在子类中实现。</p>
</dd></dl>

</dd></dl>

</div>
<div class="section" id="s-splitdatetimefield">
<span id="splitdatetimefield"></span><h3><code class="docutils literal notranslate"><span class="pre">SplitDateTimeField</span></code><a class="headerlink" href="#splitdatetimefield" title="永久链接至标题">¶</a></h3>
<dl class="class">
<dt id="django.forms.SplitDateTimeField">
<em class="property">class </em><code class="descname">SplitDateTimeField</code>(<em>**kwargs</em>)<a class="headerlink" href="#django.forms.SplitDateTimeField" title="永久链接至目标">¶</a></dt>
<dd><ul class="simple">
<li>默认部件：<a class="reference internal" href="widgets.html#django.forms.SplitDateTimeWidget" title="django.forms.SplitDateTimeWidget"><code class="xref py py-class docutils literal notranslate"><span class="pre">SplitDateTimeWidget</span></code></a></li>
<li>空值：<code class="docutils literal notranslate"><span class="pre">None</span></code></li>
<li>规范化为：Python 的 <code class="docutils literal notranslate"><span class="pre">datetime.datetime</span></code> 对象。</li>
<li>验证给定值是 <code class="docutils literal notranslate"><span class="pre">datetime.datetime</span></code> 或以特定日期时间格式化的字符串。</li>
<li>错误信息键：<code class="docutils literal notranslate"><span class="pre">required</span></code>、<code class="docutils literal notranslate"><span class="pre">invalid</span></code>、<code class="docutils literal notranslate"><span class="pre">invalid_date</span></code>、<code class="docutils literal notranslate"><span class="pre">invalid_time</span></code></li>
</ul>
<p>需要两个可选的参数：</p>
<dl class="attribute">
<dt id="django.forms.SplitDateTimeField.input_date_formats">
<code class="descname">input_date_formats</code><a class="headerlink" href="#django.forms.SplitDateTimeField.input_date_formats" title="永久链接至目标">¶</a></dt>
<dd><p>用于将字符串转换为有效的 <code class="docutils literal notranslate"><span class="pre">datetime.date</span></code> 对象的格式列表。</p>
</dd></dl>

<p>如果没有提供 <code class="docutils literal notranslate"><span class="pre">input_date_formats</span></code> 参数，则使用 <a class="reference internal" href="#django.forms.DateField" title="django.forms.DateField"><code class="xref py py-class docutils literal notranslate"><span class="pre">DateField</span></code></a> 的默认输入格式。</p>
<dl class="attribute">
<dt id="django.forms.SplitDateTimeField.input_time_formats">
<code class="descname">input_time_formats</code><a class="headerlink" href="#django.forms.SplitDateTimeField.input_time_formats" title="永久链接至目标">¶</a></dt>
<dd><p>用于将字符串转换为有效的 <code class="docutils literal notranslate"><span class="pre">datetime.time</span></code> 对象的格式列表。</p>
</dd></dl>

<p>如果没有提供 <code class="docutils literal notranslate"><span class="pre">input_time_formats</span></code> 参数，则使用 <a class="reference internal" href="#django.forms.TimeField" title="django.forms.TimeField"><code class="xref py py-class docutils literal notranslate"><span class="pre">TimeField</span></code></a> 的默认输入格式。</p>
</dd></dl>

</div>
</div>
<div class="section" id="s-fields-which-handle-relationships">
<span id="s-id2"></span><span id="fields-which-handle-relationships"></span><span id="id2"></span><h2>处理关系的字段<a class="headerlink" href="#fields-which-handle-relationships" title="永久链接至标题">¶</a></h2>
<p>有两个字段可用于表示模型之间的关系： <a class="reference internal" href="#django.forms.ModelChoiceField" title="django.forms.ModelChoiceField"><code class="xref py py-class docutils literal notranslate"><span class="pre">ModelChoiceField</span></code></a> 和 <a class="reference internal" href="#django.forms.ModelMultipleChoiceField" title="django.forms.ModelMultipleChoiceField"><code class="xref py py-class docutils literal notranslate"><span class="pre">ModelMultipleChoiceField</span></code></a>。 这两个字段都需要一个 <code class="docutils literal notranslate"><span class="pre">queryset</span></code> 参数，用于创建字段的选择。 在表单验证后，这些字段将把一个模型对象（对于 <code class="docutils literal notranslate"><span class="pre">ModelChoiceField</span></code>）或多个模型对象（对于 <code class="docutils literal notranslate"><span class="pre">ModelMultipleChoiceField</span></code>）放入表单的 <code class="docutils literal notranslate"><span class="pre">cleaned_data</span></code> 字典中。</p>
<p>对于更复杂的用途，你可以在声明表单字段时指定 <code class="docutils literal notranslate"><span class="pre">queryset=None</span></code>，然后在表单的 <code class="docutils literal notranslate"><span class="pre">__init__()</span></code> 方法中填充 <code class="docutils literal notranslate"><span class="pre">queryset</span></code>：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">FooMultipleChoiceForm</span><span class="p">(</span><span class="n">forms</span><span class="o">.</span><span class="n">Form</span><span class="p">):</span>
    <span class="n">foo_select</span> <span class="o">=</span> <span class="n">forms</span><span class="o">.</span><span class="n">ModelMultipleChoiceField</span><span class="p">(</span><span class="n">queryset</span><span class="o">=</span><span class="kc">None</span><span class="p">)</span>

    <span class="k">def</span> <span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
        <span class="nb">super</span><span class="p">()</span><span class="o">.</span><span class="fm">__init__</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">fields</span><span class="p">[</span><span class="s1">&#39;foo_select&#39;</span><span class="p">]</span><span class="o">.</span><span class="n">queryset</span> <span class="o">=</span> <span class="o">...</span>
</pre></div>
</div>
<p><code class="docutils literal notranslate"><span class="pre">ModelChoiceField</span></code> 和 <code class="docutils literal notranslate"><span class="pre">ModelMultipleChoiceField</span></code> 都有一个 <code class="docutils literal notranslate"><span class="pre">iterator</span></code> 属性，它指定了在生成选择时用于迭代查询集的类。详见 <a class="reference internal" href="#iterating-relationship-choices"><span class="std std-ref">迭代关系选择</span></a>。</p>
<div class="section" id="s-modelchoicefield">
<span id="modelchoicefield"></span><h3><code class="docutils literal notranslate"><span class="pre">ModelChoiceField</span></code><a class="headerlink" href="#modelchoicefield" title="永久链接至标题">¶</a></h3>
<dl class="class">
<dt id="django.forms.ModelChoiceField">
<em class="property">class </em><code class="descname">ModelChoiceField</code>(<em>**kwargs</em>)<a class="headerlink" href="#django.forms.ModelChoiceField" title="永久链接至目标">¶</a></dt>
<dd><ul class="simple">
<li>默认部件：<a class="reference internal" href="widgets.html#django.forms.Select" title="django.forms.Select"><code class="xref py py-class docutils literal notranslate"><span class="pre">Select</span></code></a></li>
<li>空值：<code class="docutils literal notranslate"><span class="pre">None</span></code></li>
<li>规范化为：一个模型实例。</li>
<li>验证给定的 id 是否存在于查询集中。</li>
<li>错误信息键：<code class="docutils literal notranslate"><span class="pre">required</span></code>、<code class="docutils literal notranslate"><span class="pre">invalid_choice</span></code></li>
</ul>
<p>允许选择一个单一的模型对象，适合代表一个外键。请注意，当条目数量增加时，<code class="docutils literal notranslate"><span class="pre">ModelChoiceField</span></code> 的默认部件变得不实用。你应该避免将其用于超过 100 个项目。</p>
<p>需要一个参数：</p>
<dl class="attribute">
<dt id="django.forms.ModelChoiceField.queryset">
<code class="descname">queryset</code><a class="headerlink" href="#django.forms.ModelChoiceField.queryset" title="永久链接至目标">¶</a></dt>
<dd><p>由模型对象组成的 <code class="docutils literal notranslate"><span class="pre">QuerySet</span></code>，从中得出字段的选择，用于验证用户的选择。它在表单渲染时被执行。</p>
</dd></dl>

<p><code class="docutils literal notranslate"><span class="pre">ModelChoiceField</span></code> 也需要两个可选参数：</p>
<dl class="attribute">
<dt id="django.forms.ModelChoiceField.empty_label">
<code class="descname">empty_label</code><a class="headerlink" href="#django.forms.ModelChoiceField.empty_label" title="永久链接至目标">¶</a></dt>
<dd><p>默认情况下，<code class="docutils literal notranslate"><span class="pre">ModelChoiceField</span></code> 使用的 <code class="docutils literal notranslate"><span class="pre">&lt;select&gt;</span></code> 小组件将在列表顶部有一个空的选择。你可以用 <code class="docutils literal notranslate"><span class="pre">empty_label</span></code> 属性来改变这个标签的文本（默认是 <code class="docutils literal notranslate"><span class="pre">&quot;---------&quot;</span></code>），或者你可以通过将 <code class="docutils literal notranslate"><span class="pre">empty_label</span></code> 设置为 <code class="docutils literal notranslate"><span class="pre">None</span></code> 来完全禁用空标签。</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># A custom empty label</span>
<span class="n">field1</span> <span class="o">=</span> <span class="n">forms</span><span class="o">.</span><span class="n">ModelChoiceField</span><span class="p">(</span><span class="n">queryset</span><span class="o">=...</span><span class="p">,</span> <span class="n">empty_label</span><span class="o">=</span><span class="s2">&quot;(Nothing)&quot;</span><span class="p">)</span>

<span class="c1"># No empty label</span>
<span class="n">field2</span> <span class="o">=</span> <span class="n">forms</span><span class="o">.</span><span class="n">ModelChoiceField</span><span class="p">(</span><span class="n">queryset</span><span class="o">=...</span><span class="p">,</span> <span class="n">empty_label</span><span class="o">=</span><span class="kc">None</span><span class="p">)</span>
</pre></div>
</div>
<p>请注意，如果 <code class="docutils literal notranslate"><span class="pre">ModelChoiceField</span></code> 是必需的，并且有一个默认的初始值，则不会创建空的选择（无论 <code class="docutils literal notranslate"><span class="pre">empty_label</span></code> 的值如何）。</p>
</dd></dl>

<dl class="attribute">
<dt id="django.forms.ModelChoiceField.to_field_name">
<code class="descname">to_field_name</code><a class="headerlink" href="#django.forms.ModelChoiceField.to_field_name" title="永久链接至目标">¶</a></dt>
<dd><p>这个可选参数用于指定字段，作为字段的小组件中选择的值。请确保它是模型的唯一字段，否则所选的值可能会匹配多个对象。默认情况下，它被设置为 <code class="docutils literal notranslate"><span class="pre">None</span></code>，在这种情况下，将使用每个对象的主键。例如：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># No custom to_field_name</span>
<span class="n">field1</span> <span class="o">=</span> <span class="n">forms</span><span class="o">.</span><span class="n">ModelChoiceField</span><span class="p">(</span><span class="n">queryset</span><span class="o">=...</span><span class="p">)</span>
</pre></div>
</div>
<p>会产生：</p>
<div class="highlight-html notranslate"><div class="highlight"><pre><span></span><span class="p">&lt;</span><span class="nt">select</span> <span class="na">id</span><span class="o">=</span><span class="s">&quot;id_field1&quot;</span> <span class="na">name</span><span class="o">=</span><span class="s">&quot;field1&quot;</span><span class="p">&gt;</span>
<span class="p">&lt;</span><span class="nt">option</span> <span class="na">value</span><span class="o">=</span><span class="s">&quot;obj1.pk&quot;</span><span class="p">&gt;</span>Object1<span class="p">&lt;/</span><span class="nt">option</span><span class="p">&gt;</span>
<span class="p">&lt;</span><span class="nt">option</span> <span class="na">value</span><span class="o">=</span><span class="s">&quot;obj2.pk&quot;</span><span class="p">&gt;</span>Object2<span class="p">&lt;/</span><span class="nt">option</span><span class="p">&gt;</span>
...
<span class="p">&lt;/</span><span class="nt">select</span><span class="p">&gt;</span>
</pre></div>
</div>
<p>和：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># to_field_name provided</span>
<span class="n">field2</span> <span class="o">=</span> <span class="n">forms</span><span class="o">.</span><span class="n">ModelChoiceField</span><span class="p">(</span><span class="n">queryset</span><span class="o">=...</span><span class="p">,</span> <span class="n">to_field_name</span><span class="o">=</span><span class="s2">&quot;name&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>会产生：</p>
<div class="highlight-html notranslate"><div class="highlight"><pre><span></span><span class="p">&lt;</span><span class="nt">select</span> <span class="na">id</span><span class="o">=</span><span class="s">&quot;id_field2&quot;</span> <span class="na">name</span><span class="o">=</span><span class="s">&quot;field2&quot;</span><span class="p">&gt;</span>
<span class="p">&lt;</span><span class="nt">option</span> <span class="na">value</span><span class="o">=</span><span class="s">&quot;obj1.name&quot;</span><span class="p">&gt;</span>Object1<span class="p">&lt;/</span><span class="nt">option</span><span class="p">&gt;</span>
<span class="p">&lt;</span><span class="nt">option</span> <span class="na">value</span><span class="o">=</span><span class="s">&quot;obj2.name&quot;</span><span class="p">&gt;</span>Object2<span class="p">&lt;/</span><span class="nt">option</span><span class="p">&gt;</span>
...
<span class="p">&lt;/</span><span class="nt">select</span><span class="p">&gt;</span>
</pre></div>
</div>
</dd></dl>

<p><code class="docutils literal notranslate"><span class="pre">ModelChoiceField</span></code> 也有属性：</p>
<dl class="attribute">
<dt id="django.forms.ModelChoiceField.iterator">
<code class="descname">iterator</code><a class="headerlink" href="#django.forms.ModelChoiceField.iterator" title="永久链接至目标">¶</a></dt>
<dd><p>用于从 <code class="docutils literal notranslate"><span class="pre">queryset</span></code> 中生成字段选择的迭代器类。默认情况下， <a class="reference internal" href="#django.forms.ModelChoiceIterator" title="django.forms.ModelChoiceIterator"><code class="xref py py-class docutils literal notranslate"><span class="pre">ModelChoiceIterator</span></code></a>。</p>
</dd></dl>

<p>模型的 <code class="docutils literal notranslate"><span class="pre">__str__()</span></code> 方法将被调用，以生成用于字段选择的对象的字符串表示。要提供自定义的表示，请将 <code class="docutils literal notranslate"><span class="pre">ModelChoiceField</span></code> 子类化，并覆盖 <code class="docutils literal notranslate"><span class="pre">label_from_instance</span></code>。该方法将接收一个模型对象，并应返回一个适合表示它的字符串。例如：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.forms</span> <span class="kn">import</span> <span class="n">ModelChoiceField</span>

<span class="k">class</span> <span class="nc">MyModelChoiceField</span><span class="p">(</span><span class="n">ModelChoiceField</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">label_from_instance</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">obj</span><span class="p">):</span>
        <span class="k">return</span> <span class="s2">&quot;My Object #</span><span class="si">%i</span><span class="s2">&quot;</span> <span class="o">%</span> <span class="n">obj</span><span class="o">.</span><span class="n">id</span>
</pre></div>
</div>
</dd></dl>

</div>
<div class="section" id="s-modelmultiplechoicefield">
<span id="modelmultiplechoicefield"></span><h3><code class="docutils literal notranslate"><span class="pre">ModelMultipleChoiceField</span></code><a class="headerlink" href="#modelmultiplechoicefield" title="永久链接至标题">¶</a></h3>
<dl class="class">
<dt id="django.forms.ModelMultipleChoiceField">
<em class="property">class </em><code class="descname">ModelMultipleChoiceField</code>(<em>**kwargs</em>)<a class="headerlink" href="#django.forms.ModelMultipleChoiceField" title="永久链接至目标">¶</a></dt>
<dd><ul class="simple">
<li>默认部件：<a class="reference internal" href="widgets.html#django.forms.SelectMultiple" title="django.forms.SelectMultiple"><code class="xref py py-class docutils literal notranslate"><span class="pre">SelectMultiple</span></code></a></li>
<li>空值：一个空的 <code class="docutils literal notranslate"><span class="pre">QuerySet</span></code> （<code class="docutils literal notranslate"><span class="pre">self.queryset.none()</span></code>）。</li>
<li>规范化为：一个模型实例的 <code class="docutils literal notranslate"><span class="pre">QuerySet</span></code>。</li>
<li>验证给定值列表中的每个 id 是否存在于查询集中。</li>
<li>错误信息键：<code class="docutils literal notranslate"><span class="pre">required</span></code>、<code class="docutils literal notranslate"><span class="pre">invalid_list</span></code>、<code class="docutils literal notranslate"><span class="pre">invalid_choice</span></code>、<code class="docutils literal notranslate"><span class="pre">invalid_pk_value</span></code></li>
</ul>
<p><code class="docutils literal notranslate"><span class="pre">invalid_choice</span></code> 信息可能包含 <code class="docutils literal notranslate"><span class="pre">%(value)s</span></code>，<code class="docutils literal notranslate"><span class="pre">invalid_pk_value</span></code> 信息可能包含 <code class="docutils literal notranslate"><span class="pre">%(pk)s</span></code>，将用适当的值代替。</p>
<p>允许选择一个或多个模型对象，适合表示多对多关系。与 <a class="reference internal" href="#django.forms.ModelChoiceField" title="django.forms.ModelChoiceField"><code class="xref py py-class docutils literal notranslate"><span class="pre">ModelChoiceField</span></code></a> 一样，你可以使用 <code class="docutils literal notranslate"><span class="pre">label_from_instance</span></code> 来自定义对象的表示。</p>
<p>需要一个参数：</p>
<dl class="attribute">
<dt id="django.forms.ModelMultipleChoiceField.queryset">
<code class="descname">queryset</code><a class="headerlink" href="#django.forms.ModelMultipleChoiceField.queryset" title="永久链接至目标">¶</a></dt>
<dd><p>与 <a class="reference internal" href="#django.forms.ModelChoiceField.queryset" title="django.forms.ModelChoiceField.queryset"><code class="xref py py-class docutils literal notranslate"><span class="pre">ModelChoiceField.queryset</span></code></a> 相同。</p>
</dd></dl>

<p>需要一个可选的参数：</p>
<dl class="attribute">
<dt id="django.forms.ModelMultipleChoiceField.to_field_name">
<code class="descname">to_field_name</code><a class="headerlink" href="#django.forms.ModelMultipleChoiceField.to_field_name" title="永久链接至目标">¶</a></dt>
<dd><p>与 <a class="reference internal" href="#django.forms.ModelChoiceField.to_field_name" title="django.forms.ModelChoiceField.to_field_name"><code class="xref py py-class docutils literal notranslate"><span class="pre">ModelChoiceField.to_field_name</span></code></a> 相同。</p>
</dd></dl>

<p><code class="docutils literal notranslate"><span class="pre">ModelMultipleChoiceField</span></code> 也有属性：</p>
<dl class="attribute">
<dt id="django.forms.ModelMultipleChoiceField.iterator">
<code class="descname">iterator</code><a class="headerlink" href="#django.forms.ModelMultipleChoiceField.iterator" title="永久链接至目标">¶</a></dt>
<dd><p>与 <a class="reference internal" href="#django.forms.ModelChoiceField.iterator" title="django.forms.ModelChoiceField.iterator"><code class="xref py py-class docutils literal notranslate"><span class="pre">ModelChoiceField.iterator</span></code></a> 相同。</p>
</dd></dl>

</dd></dl>

<div class="deprecated">
<p><span class="versionmodified">3.1 版后已移除: </span><code class="docutils literal notranslate"><span class="pre">list</span></code> 消息已不适用，请使用 <code class="docutils literal notranslate"><span class="pre">invalid_list</span></code> 代替。</p>
</div>
</div>
<div class="section" id="s-iterating-relationship-choices">
<span id="s-id3"></span><span id="iterating-relationship-choices"></span><span id="id3"></span><h3>迭代关系选择<a class="headerlink" href="#iterating-relationship-choices" title="永久链接至标题">¶</a></h3>
<p>默认情况下， <a class="reference internal" href="#django.forms.ModelChoiceField" title="django.forms.ModelChoiceField"><code class="xref py py-class docutils literal notranslate"><span class="pre">ModelChoiceField</span></code></a> 和 <a class="reference internal" href="#django.forms.ModelMultipleChoiceField" title="django.forms.ModelMultipleChoiceField"><code class="xref py py-class docutils literal notranslate"><span class="pre">ModelMultipleChoiceField</span></code></a> 使用 <a class="reference internal" href="#django.forms.ModelChoiceIterator" title="django.forms.ModelChoiceIterator"><code class="xref py py-class docutils literal notranslate"><span class="pre">ModelChoiceIterator</span></code></a> 来生成它们的字段 <code class="docutils literal notranslate"><span class="pre">choices</span></code>。</p>
<p>When iterated, <code class="docutils literal notranslate"><span class="pre">ModelChoiceIterator</span></code> yields 2-tuple choices containing
<a class="reference internal" href="#django.forms.ModelChoiceIteratorValue" title="django.forms.ModelChoiceIteratorValue"><code class="xref py py-class docutils literal notranslate"><span class="pre">ModelChoiceIteratorValue</span></code></a> instances as the first <code class="docutils literal notranslate"><span class="pre">value</span></code> element in
each choice. <code class="docutils literal notranslate"><span class="pre">ModelChoiceIteratorValue</span></code> wraps the choice value while
maintaining a reference to the source model instance that can be used in custom
widget implementations, for example, to add <a class="reference external" href="https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/data-*">data-* attributes</a> to
<code class="docutils literal notranslate"><span class="pre">&lt;option&gt;</span></code> elements.</p>
<p>例如，考虑以下模型：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.db</span> <span class="kn">import</span> <span class="n">models</span>

<span class="k">class</span> <span class="nc">Topping</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">name</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">100</span><span class="p">)</span>
    <span class="n">price</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">DecimalField</span><span class="p">(</span><span class="n">decimal_places</span><span class="o">=</span><span class="mi">2</span><span class="p">,</span> <span class="n">max_digits</span><span class="o">=</span><span class="mi">6</span><span class="p">)</span>

    <span class="k">def</span> <span class="fm">__str__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">name</span>

<span class="k">class</span> <span class="nc">Pizza</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">topping</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">ForeignKey</span><span class="p">(</span><span class="n">Topping</span><span class="p">,</span> <span class="n">on_delete</span><span class="o">=</span><span class="n">models</span><span class="o">.</span><span class="n">CASCADE</span><span class="p">)</span>
</pre></div>
</div>
<p>你可以使用 <a class="reference internal" href="widgets.html#django.forms.Select" title="django.forms.Select"><code class="xref py py-class docutils literal notranslate"><span class="pre">Select</span></code></a> 部件子类将 <code class="docutils literal notranslate"><span class="pre">Topping.price</span></code> 的值作为 HTML 属性 <code class="docutils literal notranslate"><span class="pre">data-price</span></code>，包含在每个 <code class="docutils literal notranslate"><span class="pre">&lt;option&gt;</span></code> 元素中：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django</span> <span class="kn">import</span> <span class="n">forms</span>

<span class="k">class</span> <span class="nc">ToppingSelect</span><span class="p">(</span><span class="n">forms</span><span class="o">.</span><span class="n">Select</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">create_option</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">name</span><span class="p">,</span> <span class="n">value</span><span class="p">,</span> <span class="n">label</span><span class="p">,</span> <span class="n">selected</span><span class="p">,</span> <span class="n">index</span><span class="p">,</span> <span class="n">subindex</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">attrs</span><span class="o">=</span><span class="kc">None</span><span class="p">):</span>
        <span class="n">option</span> <span class="o">=</span> <span class="nb">super</span><span class="p">()</span><span class="o">.</span><span class="n">create_option</span><span class="p">(</span><span class="n">name</span><span class="p">,</span> <span class="n">value</span><span class="p">,</span> <span class="n">label</span><span class="p">,</span> <span class="n">selected</span><span class="p">,</span> <span class="n">index</span><span class="p">,</span> <span class="n">subindex</span><span class="p">,</span> <span class="n">attrs</span><span class="p">)</span>
        <span class="k">if</span> <span class="n">value</span><span class="p">:</span>
            <span class="n">option</span><span class="p">[</span><span class="s1">&#39;attrs&#39;</span><span class="p">][</span><span class="s1">&#39;data-price&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="n">value</span><span class="o">.</span><span class="n">instance</span><span class="o">.</span><span class="n">price</span>
        <span class="k">return</span> <span class="n">option</span>

<span class="k">class</span> <span class="nc">PizzaForm</span><span class="p">(</span><span class="n">forms</span><span class="o">.</span><span class="n">ModelForm</span><span class="p">):</span>
    <span class="k">class</span> <span class="nc">Meta</span><span class="p">:</span>
        <span class="n">model</span> <span class="o">=</span> <span class="n">Pizza</span>
        <span class="n">fields</span> <span class="o">=</span> <span class="p">[</span><span class="s1">&#39;topping&#39;</span><span class="p">]</span>
        <span class="n">widgets</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;topping&#39;</span><span class="p">:</span> <span class="n">ToppingSelect</span><span class="p">}</span>
</pre></div>
</div>
<p>这将使 <code class="docutils literal notranslate"><span class="pre">Pizza.topping</span></code> 选择为：</p>
<div class="highlight-html notranslate"><div class="highlight"><pre><span></span><span class="p">&lt;</span><span class="nt">select</span> <span class="na">id</span><span class="o">=</span><span class="s">&quot;id_topping&quot;</span> <span class="na">name</span><span class="o">=</span><span class="s">&quot;topping&quot;</span> <span class="na">required</span><span class="p">&gt;</span>
<span class="p">&lt;</span><span class="nt">option</span> <span class="na">value</span><span class="o">=</span><span class="s">&quot;&quot;</span> <span class="na">selected</span><span class="p">&gt;</span>---------<span class="p">&lt;/</span><span class="nt">option</span><span class="p">&gt;</span>
<span class="p">&lt;</span><span class="nt">option</span> <span class="na">value</span><span class="o">=</span><span class="s">&quot;1&quot;</span> <span class="na">data-price</span><span class="o">=</span><span class="s">&quot;1.50&quot;</span><span class="p">&gt;</span>mushrooms<span class="p">&lt;/</span><span class="nt">option</span><span class="p">&gt;</span>
<span class="p">&lt;</span><span class="nt">option</span> <span class="na">value</span><span class="o">=</span><span class="s">&quot;2&quot;</span> <span class="na">data-price</span><span class="o">=</span><span class="s">&quot;1.25&quot;</span><span class="p">&gt;</span>onions<span class="p">&lt;/</span><span class="nt">option</span><span class="p">&gt;</span>
<span class="p">&lt;</span><span class="nt">option</span> <span class="na">value</span><span class="o">=</span><span class="s">&quot;3&quot;</span> <span class="na">data-price</span><span class="o">=</span><span class="s">&quot;1.75&quot;</span><span class="p">&gt;</span>peppers<span class="p">&lt;/</span><span class="nt">option</span><span class="p">&gt;</span>
<span class="p">&lt;</span><span class="nt">option</span> <span class="na">value</span><span class="o">=</span><span class="s">&quot;4&quot;</span> <span class="na">data-price</span><span class="o">=</span><span class="s">&quot;2.00&quot;</span><span class="p">&gt;</span>pineapple<span class="p">&lt;/</span><span class="nt">option</span><span class="p">&gt;</span>
<span class="p">&lt;/</span><span class="nt">select</span><span class="p">&gt;</span>
</pre></div>
</div>
<p>对于更高级的用法，你可以将 <code class="docutils literal notranslate"><span class="pre">ModelChoiceIterator</span></code> 子类化，以自定义产生的二元元组选择。</p>
<div class="section" id="s-modelchoiceiterator">
<span id="modelchoiceiterator"></span><h4><code class="docutils literal notranslate"><span class="pre">ModelChoiceIterator</span></code><a class="headerlink" href="#modelchoiceiterator" title="永久链接至标题">¶</a></h4>
<dl class="class">
<dt id="django.forms.ModelChoiceIterator">
<em class="property">class </em><code class="descname">ModelChoiceIterator</code>(<em>field</em>)<a class="headerlink" href="#django.forms.ModelChoiceIterator" title="永久链接至目标">¶</a></dt>
<dd><p>指定给 <code class="xref py py-class docutils literal notranslate"><span class="pre">ModelChoiceField`和:class:`ModelMultipleChoiceField</span></code> 的 <code class="docutils literal notranslate"><span class="pre">iterator</span></code> 属性的默认类。迭代器，从查询集中产生二元元组选择。</p>
<p>需要一个参数：</p>
<dl class="attribute">
<dt id="django.forms.ModelChoiceIterator.field">
<code class="descname">field</code><a class="headerlink" href="#django.forms.ModelChoiceIterator.field" title="永久链接至目标">¶</a></dt>
<dd><p><code class="docutils literal notranslate"><span class="pre">ModelChoiceField</span></code> 或 <code class="docutils literal notranslate"><span class="pre">ModelMultipleChoiceField</span></code> 的实例来迭代和产生选择。</p>
</dd></dl>

<p><code class="docutils literal notranslate"><span class="pre">ModelChoiceIter</span></code> 有以下方法：</p>
<dl class="method">
<dt id="django.forms.ModelChoiceIterator.__iter__">
<code class="descname">__iter__</code>()<a class="headerlink" href="#django.forms.ModelChoiceIterator.__iter__" title="永久链接至目标">¶</a></dt>
<dd><p>产生二元元组选择，格式为 <code class="xref py py-attr docutils literal notranslate"><span class="pre">ChoiceField.chips</span></code> 使用的 <code class="docutils literal notranslate"><span class="pre">(value,</span> <span class="pre">label)</span></code>。第一个 <code class="docutils literal notranslate"><span class="pre">value</span></code> 元素是一个 <a class="reference internal" href="#django.forms.ModelChoiceIteratorValue" title="django.forms.ModelChoiceIteratorValue"><code class="xref py py-class docutils literal notranslate"><span class="pre">ModelChoiceIteratorValue</span></code></a> 实例。</p>
<div class="versionchanged">
<span class="title">Changed in Django 3.1:</span> <p>在旧版本中，选择元组中的第一个 <code class="docutils literal notranslate"><span class="pre">value</span></code> 元素是 <code class="docutils literal notranslate"><span class="pre">field</span></code> 值本身，而不是 <code class="docutils literal notranslate"><span class="pre">ModelChoiceIteratorValue</span></code> 实例。在大多数情况下，这个代理是透明的，但如果你需要 <code class="docutils literal notranslate"><span class="pre">field</span></code> 值本身，请使用 <a class="reference internal" href="#django.forms.ModelChoiceIteratorValue.value" title="django.forms.ModelChoiceIteratorValue.value"><code class="xref py py-attr docutils literal notranslate"><span class="pre">ModelChoiceIteratorValue.value</span></code></a> 属性代替。</p>
</div>
</dd></dl>

</dd></dl>

</div>
<div class="section" id="s-modelchoiceiteratorvalue">
<span id="modelchoiceiteratorvalue"></span><h4><code class="docutils literal notranslate"><span class="pre">ModelChoiceIteratorValue</span></code><a class="headerlink" href="#modelchoiceiteratorvalue" title="永久链接至标题">¶</a></h4>
<dl class="class">
<dt id="django.forms.ModelChoiceIteratorValue">
<em class="property">class </em><code class="descname">ModelChoiceIteratorValue</code>(<em>value</em>, <em>instance</em>)<a class="headerlink" href="#django.forms.ModelChoiceIteratorValue" title="永久链接至目标">¶</a></dt>
<dd><div class="versionadded">
<span class="title">New in Django 3.1.</span> </div>
<p>需要两个参数：</p>
<dl class="attribute">
<dt id="django.forms.ModelChoiceIteratorValue.value">
<code class="descname">value</code><a class="headerlink" href="#django.forms.ModelChoiceIteratorValue.value" title="永久链接至目标">¶</a></dt>
<dd><p>选择的值。该值用于呈现 HTML <code class="docutils literal notranslate"><span class="pre">&lt;option&gt;</span></code> 元素的 <code class="docutils literal notranslate"><span class="pre">value</span></code> 属性。</p>
</dd></dl>

<dl class="attribute">
<dt id="django.forms.ModelChoiceIteratorValue.instance">
<code class="descname">instance</code><a class="headerlink" href="#django.forms.ModelChoiceIteratorValue.instance" title="永久链接至目标">¶</a></dt>
<dd><p>来自查询集的模型实例。该实例可以在自定义的 <code class="docutils literal notranslate"><span class="pre">ChoiceWidget.create_option()</span></code> 实现中被访问，以调整渲染的 HTML。</p>
</dd></dl>

<p><code class="docutils literal notranslate"><span class="pre">ModelChoiceIteratorValue</span></code> 有以下方法：</p>
<dl class="method">
<dt id="django.forms.ModelChoiceIteratorValue.__str__">
<code class="descname">__str__</code>()<a class="headerlink" href="#django.forms.ModelChoiceIteratorValue.__str__" title="永久链接至目标">¶</a></dt>
<dd><p>返回 <code class="docutils literal notranslate"><span class="pre">value</span></code> 作为一个字符串在 HTML 中显示。</p>
</dd></dl>

</dd></dl>

</div>
</div>
</div>
<div class="section" id="s-creating-custom-fields">
<span id="creating-custom-fields"></span><h2>创建自定义字段<a class="headerlink" href="#creating-custom-fields" title="永久链接至标题">¶</a></h2>
<p>如果内置的 <code class="docutils literal notranslate"><span class="pre">Field</span></code> 类不能满足你的需求，你可以创建自定义的 <code class="docutils literal notranslate"><span class="pre">Field</span></code> 类。为此，创建一个 <code class="docutils literal notranslate"><span class="pre">django.forms.Field</span></code> 的子类。它唯一的要求是实现一个 <code class="docutils literal notranslate"><span class="pre">clean()</span></code> 方法，并且它的 <code class="docutils literal notranslate"><span class="pre">__init__()</span></code> 方法接受上面提到的核心参数 (<code class="docutils literal notranslate"><span class="pre">required</span></code>, <code class="docutils literal notranslate"><span class="pre">label</span></code>, <code class="docutils literal notranslate"><span class="pre">initial</span></code>, <code class="docutils literal notranslate"><span class="pre">widget</span></code>, <code class="docutils literal notranslate"><span class="pre">help_text</span></code>)。</p>
<p>你也可以通过覆盖 <a class="reference internal" href="api.html#django.forms.Field.get_bound_field" title="django.forms.Field.get_bound_field"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get_bound_field()</span></code></a> 来自定义字段的访问方式。</p>
</div>
</div>


          </div>
        </div>
      </div>
      
        
          <div class="yui-b" id="sidebar">
            
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../../contents.html">Table of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">表单字段</a><ul>
<li><a class="reference internal" href="#core-field-arguments">核心字段参数</a><ul>
<li><a class="reference internal" href="#required"><code class="docutils literal notranslate"><span class="pre">required</span></code></a></li>
<li><a class="reference internal" href="#label"><code class="docutils literal notranslate"><span class="pre">label</span></code></a></li>
<li><a class="reference internal" href="#label-suffix"><code class="docutils literal notranslate"><span class="pre">label_suffix</span></code></a></li>
<li><a class="reference internal" href="#initial"><code class="docutils literal notranslate"><span class="pre">initial</span></code></a></li>
<li><a class="reference internal" href="#widget"><code class="docutils literal notranslate"><span class="pre">widget</span></code></a></li>
<li><a class="reference internal" href="#help-text"><code class="docutils literal notranslate"><span class="pre">help_text</span></code></a></li>
<li><a class="reference internal" href="#error-messages"><code class="docutils literal notranslate"><span class="pre">error_messages</span></code></a></li>
<li><a class="reference internal" href="#validators"><code class="docutils literal notranslate"><span class="pre">validators</span></code></a></li>
<li><a class="reference internal" href="#localize"><code class="docutils literal notranslate"><span class="pre">localize</span></code></a></li>
<li><a class="reference internal" href="#disabled"><code class="docutils literal notranslate"><span class="pre">disabled</span></code></a></li>
</ul>
</li>
<li><a class="reference internal" href="#checking-if-the-field-data-has-changed">检查字段数据是否有变化</a><ul>
<li><a class="reference internal" href="#has-changed"><code class="docutils literal notranslate"><span class="pre">has_changed()</span></code></a></li>
</ul>
</li>
<li><a class="reference internal" href="#built-in-field-classes">内置 <code class="docutils literal notranslate"><span class="pre">Field</span></code> 类</a><ul>
<li><a class="reference internal" href="#booleanfield"><code class="docutils literal notranslate"><span class="pre">BooleanField</span></code></a></li>
<li><a class="reference internal" href="#charfield"><code class="docutils literal notranslate"><span class="pre">CharField</span></code></a></li>
<li><a class="reference internal" href="#choicefield"><code class="docutils literal notranslate"><span class="pre">ChoiceField</span></code></a></li>
<li><a class="reference internal" href="#typedchoicefield"><code class="docutils literal notranslate"><span class="pre">TypedChoiceField</span></code></a></li>
<li><a class="reference internal" href="#datefield"><code class="docutils literal notranslate"><span class="pre">DateField</span></code></a></li>
<li><a class="reference internal" href="#datetimefield"><code class="docutils literal notranslate"><span class="pre">DateTimeField</span></code></a></li>
<li><a class="reference internal" href="#decimalfield"><code class="docutils literal notranslate"><span class="pre">DecimalField</span></code></a></li>
<li><a class="reference internal" href="#durationfield"><code class="docutils literal notranslate"><span class="pre">DurationField</span></code></a></li>
<li><a class="reference internal" href="#emailfield"><code class="docutils literal notranslate"><span class="pre">EmailField</span></code></a></li>
<li><a class="reference internal" href="#filefield"><code class="docutils literal notranslate"><span class="pre">FileField</span></code></a></li>
<li><a class="reference internal" href="#filepathfield"><code class="docutils literal notranslate"><span class="pre">FilePathField</span></code></a></li>
<li><a class="reference internal" href="#floatfield"><code class="docutils literal notranslate"><span class="pre">FloatField</span></code></a></li>
<li><a class="reference internal" href="#imagefield"><code class="docutils literal notranslate"><span class="pre">ImageField</span></code></a></li>
<li><a class="reference internal" href="#integerfield"><code class="docutils literal notranslate"><span class="pre">IntegerField</span></code></a></li>
<li><a class="reference internal" href="#jsonfield"><code class="docutils literal notranslate"><span class="pre">JSONField</span></code></a></li>
<li><a class="reference internal" href="#genericipaddressfield"><code class="docutils literal notranslate"><span class="pre">GenericIPAddressField</span></code></a></li>
<li><a class="reference internal" href="#multiplechoicefield"><code class="docutils literal notranslate"><span class="pre">MultipleChoiceField</span></code></a></li>
<li><a class="reference internal" href="#typedmultiplechoicefield"><code class="docutils literal notranslate"><span class="pre">TypedMultipleChoiceField</span></code></a></li>
<li><a class="reference internal" href="#nullbooleanfield"><code class="docutils literal notranslate"><span class="pre">NullBooleanField</span></code></a></li>
<li><a class="reference internal" href="#regexfield"><code class="docutils literal notranslate"><span class="pre">RegexField</span></code></a></li>
<li><a class="reference internal" href="#slugfield"><code class="docutils literal notranslate"><span class="pre">SlugField</span></code></a></li>
<li><a class="reference internal" href="#timefield"><code class="docutils literal notranslate"><span class="pre">TimeField</span></code></a></li>
<li><a class="reference internal" href="#urlfield"><code class="docutils literal notranslate"><span class="pre">URLField</span></code></a></li>
<li><a class="reference internal" href="#uuidfield"><code class="docutils literal notranslate"><span class="pre">UUIDField</span></code></a></li>
</ul>
</li>
<li><a class="reference internal" href="#slightly-complex-built-in-field-classes">稍复杂的内置 <code class="docutils literal notranslate"><span class="pre">Field</span></code> 类</a><ul>
<li><a class="reference internal" href="#combofield"><code class="docutils literal notranslate"><span class="pre">ComboField</span></code></a></li>
<li><a class="reference internal" href="#multivaluefield"><code class="docutils literal notranslate"><span class="pre">MultiValueField</span></code></a></li>
<li><a class="reference internal" href="#splitdatetimefield"><code class="docutils literal notranslate"><span class="pre">SplitDateTimeField</span></code></a></li>
</ul>
</li>
<li><a class="reference internal" href="#fields-which-handle-relationships">处理关系的字段</a><ul>
<li><a class="reference internal" href="#modelchoicefield"><code class="docutils literal notranslate"><span class="pre">ModelChoiceField</span></code></a></li>
<li><a class="reference internal" href="#modelmultiplechoicefield"><code class="docutils literal notranslate"><span class="pre">ModelMultipleChoiceField</span></code></a></li>
<li><a class="reference internal" href="#iterating-relationship-choices">迭代关系选择</a><ul>
<li><a class="reference internal" href="#modelchoiceiterator"><code class="docutils literal notranslate"><span class="pre">ModelChoiceIterator</span></code></a></li>
<li><a class="reference internal" href="#modelchoiceiteratorvalue"><code class="docutils literal notranslate"><span class="pre">ModelChoiceIteratorValue</span></code></a></li>
</ul>
</li>
</ul>
</li>
<li><a class="reference internal" href="#creating-custom-fields">创建自定义字段</a></li>
</ul>
</li>
</ul>

  <h4>上一个主题</h4>
  <p class="topless"><a href="api.html"
                        title="上一章">表单 API</a></p>
  <h4>下一个主题</h4>
  <p class="topless"><a href="models.html"
                        title="下一章">模型表单函数</a></p>
  <div role="note" aria-label="source link">
    <h3>本页</h3>
    <ul class="this-page-menu">
      <li><a href="../../_sources/ref/forms/fields.txt"
            rel="nofollow">显示源代码</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>快速搜索</h3>
    <div class="searchformwrapper">
    <form class="search" action="../../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="转向" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
              <h3>Last update:</h3>
              <p class="topless">12月 07, 2021</p>
          </div>
        
      
    </div>

    <div id="ft">
      <div class="nav">
    &laquo; <a href="api.html" title="表单 API">previous</a>
     |
    <a href="../index.html" title="API 参考" accesskey="U">up</a>
   |
    <a href="models.html" title="模型表单函数">next</a> &raquo;</div>
    </div>
  </div>

      <div class="clearer"></div>
    </div>
  </body>
</html>